Frage

I need to simulate command line, therefore I need to change string into the args[] in the same way running program with parameters into main method does.

I am using commons cli, but it does not have any parsing method, it does expect array of string already.

I thought, I just use split, but unfortunately, look at this problem :

String input = "-command \"This is a long parameter\"";
String args[] = input.split(" ");
//args[0] = -command
//args[1] = "This
//args[2] = is
//etc.

If you use this -command "This is a long parameter" as parameter to your main method, you get following :

//args[0] == -command
//args[1] == This is a long parameter

So any suggestion how to do it? The second problem is to find this on google, because every single thread explains whats args[] is, not how to get it from string.

War es hilfreich?

Lösung

You can use regex to cut your string.

for (String s : "hello \"world this is\" a string"
        .split(" (?=\")|(?<=\")\\s"))
    System.out.println(s);

the code above will display:

hello 
"world this is"
a string
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top