Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting at space if not between quotes

Tags:

java

regex

i tried this:

 +|(?!(\"[^"]*\"))

but it didn't work. what can i else do to make it work? btw im using java's string.split().

like image 867
TheBreadCat Avatar asked Dec 03 '22 08:12

TheBreadCat


1 Answers

Try this:

[ ]+(?=([^"]*"[^"]*")*[^"]*$)

which will split on one or more spaces only if those spaces are followed by zero, or an even number of quotes (all the way to the end of the string!).

The following demo:

public class Main {
    public static void main(String[] args) {
        String text = "a \"b c d\" e \"f g\" h";
        System.out.println("text = " + text + "\n");
        for(String t : text.split("[ ]+(?=([^\"]*\"[^\"]*\")*[^\"]*$)")) {
            System.out.println(t);
        }
    }
}

produces the following output:

text = a "b c d" e "f g" h

a
"b c d"
e
"f g"
h
like image 95
Bart Kiers Avatar answered Dec 06 '22 11:12

Bart Kiers