如何将字符串分解为参数,尊重引号?

时间:2013-02-01 20:34:58

标签: java string split

  

可能重复:
  Regex for splitting a string using space when not surrounded by single or double quotes

如何打破这样的字符串:

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(“”),但我希望结合引号中的术语。

2 个答案:

答案 0 :(得分:4)

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

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"]

答案 1 :(得分:0)

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