使用正则表达式删除逗号和空格并将它们划分为不同的变量

Using regex to remove comma and whitespaces and divide them in different variables

有什么有效的方法吗?

我想将 arg 传递给命令行并将它们划分为以下内容:

  1. 字符串[] 命令
  2. 字符串[]字
  3. 字符串[]文件名

示例:

String[] arg = {"-b", "-f", "-i", "Dog", "Cat", "--", "fileName1.txt", "fileName2.txt", "fileName3.txt"};
Main.main(arg);

String[] arg = {"-f", "-i", "Hi", "Hello", "--", "fileName1.txt", "fileName2.txt"};
Main.main(arg);

String[] arg = {"-i", "Hi", "Hello", "--", "fileName2.txt"};
Main.main(arg);

注意:

Syntax:  "[-b] [-f] [-l] [-i]  <from> <to> -- " + "fileName"

在句法-命令中,word--fileName

"--" 每次都会在和文件名之间。

我做了以下代码,但效率不高。使用 String.split(" ") 并一次又一次地划分为效率不高的不同字符串数组。

我从来不理解使用正则表达式来处理像这样简单的事情的愿望。为什么不创建三个列表并循环遍历参数,同时将它们拆分到正确的列表中?

ArrayList<String> flags = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
ArrayList<String> files = new ArrayList<>();
for (String arg : args) {
    if (arg.equals("--")) {
        continue;
    }
    if (arg.contains(".")) {
        files.add(arg);
    }else if (arg.contains("-")) {
        flags.add(arg);
    }else {
        words.add(arg);
    }
}

一旦您将所有参数按类型拆分,您就可以轻松地对它们做任何您想做的事情,或者按照您的意愿重新排列它们。这也比正则表达式更有效。