While I was programming I found weird behavior for the java String. I am trying to parse a string as command with arguments:
Below is a screenshot of the variables during debug.
This is my code to read the command:
public List<String> readCommand(Sender sender, String command) {
boolean isInQuote = false;
List<String> splits = new ArrayList();
String current = "";
char[] arr = command.toCharArray();
for (int i = 0; i < command.toCharArray().length; i++) {
char c = arr[i];
if (c == '"') {
isInQuote = !isInQuote;
if (!isInQuote) {
splits.add(current);
current = "";
}
}
if (isInQuote) {
current += c;
} else {
if (c == ' ' || i == arr.length - 1) {
if (i == arr.length - 1) {
current += c;
}
splits.add(current);
current = "";
} else {
current += c;
}
}
}
return splits;
}
As expected in the tests; the string should be parsed as:
- "this"
- "is a test"
- "now"
instead it is parsed as:
- "this"
- "\"is a test"
- "\""
- "now"
Why don't the escaped quotes work and what am I doing wrong?
P.S.: I would try to research this subject but I don't know how to call this. Argument parsing with quotes...?
UPDATE: After your help, I discovered another bug which I fixed. The code is fully working now. All that is left now is to remake it :). The \" not working really confused me. http://pastebin.com/AdBUqJvH
First let's simplify your current attempt with:
Results:
Regex
Then you can shorten your code with
Regex
with the following (and the results are the same):