Regex to split string except specified substring

Viewed 297

I'm currently trying to split a string by whitespaces in Java, except everything between the first and last double quotes (this is a specific case and they are guaranteed to exist). I'm fairly new to regex but here's what I came up with to find the substring within the first and last quotes:

regex = ((?<=\").*(?=\"))

I have tested it out on https://regex101.com and am satisfied with the result. But now when I try to split my input string like the following:

String input = "apple \"banana\"";
String[] arr = input.split("\\s+((?<=\").*(?=\"))");

It fails to do the actual splitting. Here is the expected output:

arr[0] == "apple", arr[1] == "banana"

The output I recieve:

arr[0] == "apple \"banana\""

What am I missing here? Any guidance would be greatly appreciated.

EDIT: Answer has been given by @WiktorStribiżew in the comments.

A big thank you to everybody who helped, especially @WiktorStribiżew Cheers!

2 Answers

You should match these strings, here is a possible solution:

String input = "apple \"banana\"";
Pattern p = Pattern.compile("\"([^\"]*)\"|\\S+");
Matcher m = p.matcher(input);
List<String> results = new ArrayList<>(); // Declare a list
while (m.find()) {
    if (m.group(1) != null) {
        results.add(m.group(1));  // Add Group 1 to the list
    } else {
        results.add(m.group());   // Add the whole match value to the list
    }
}
System.out.println(results);      // Prints the resulting list

NOTE: If you plan to match all chars between the first matched " till the last ", you may use Pattern p = Pattern.compile("\"(.*)\"|\\S+");.

See the Java demo online.

Output:

apple
banana

The "([^"]*)"|\S+ pattern matches:

  • " - a " char
  • ([^"]*) - Group 1: any 0 or more chars other than "
  • " - a " char
  • | - or
  • \S+ - 1+ non-whitespace chars.
"\\s*\"++|\\s++"

apple "banana"' => 2 [[apple, banana]]

Related