1

可能重复:
当没有被单引号或双引号包围时,使用空格分割字符串的正则表达式

我怎样才能打破这样的字符串:

String args = "\"file one.txt\" filetwo.txt some other \"things here\"";

在尊重引号的同时进入其参数/参数?

所以在上面的例子中,参数将被分解为:

args[0] = file one.txt
args[1] = filetwo.txt
args[2] = some
args[3] = other
args[4] = things here

我了解如何使用 split(" "),但我想组合引号中的术语。

4

2 回答 2

5

假设您不必使用正则表达式并且您的输入不包含嵌套引号,您可以在一次迭代中通过字符串字符实现此目的:

String data = "\"file one.txt\" filetwo.txt some other \"things here\"";

List<String> tokens = new ArrayList<String>();
StringBuilder sb = new StringBuilder();

boolean insideQuote = false;

for (char c : data.toCharArray()) {

    if (c == '"')
        insideQuote = !insideQuote;

    if (c == ' ' && !insideQuote) {//when space is not inside quote split..
        tokens.add(sb.toString()); //token is ready, lets add it to list
        sb.delete(0, sb.length()); //and reset StringBuilder`s content
    } else 
        sb.append(c);//else add character to token
}
//lets not forget about last token that doesn't have space after it
tokens.add(sb.toString());

String[] array=tokens.toArray(new String[0]);
System.out.println(Arrays.toString(array));

输出:

["file one.txt", filetwo.txt, some, other, "things here"]
于 2013-02-01T22:32:18.383 回答
-1

如果您在引入依赖项时没有问题,您可以使用Apache 的Commons cli。它将简化命令行解析并使其对用户更有用。

于 2013-02-01T21:12:20.167 回答