1

Possible Duplicate:
Regex for splitting a string using space when not surrounded by single or double quotes

How can I break a string like this:

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

into its arguments / parameters while respecting quotes?

So in the above example, the arguments would be broken into:

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

I understand how to use split(" "), but I want to combine terms that are in quotes.

Community
  • 1
  • 1
Jane Panda
  • 1,591
  • 4
  • 23
  • 51

2 Answers2

5

Assuming that you don't have to use regex and your input doesn't contains nested quotes you can achieve this in one iteration over your String characters:

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));

Output:

["file one.txt", filetwo.txt, some, other, "things here"]
Pshemo
  • 122,468
  • 25
  • 185
  • 269
-1

If you haven't problems introducing a dependency you can use Commons cli from Apache. It will simplify command line parsing and make it more usable for users.

lujop
  • 13,504
  • 9
  • 62
  • 95