TheBreadCat
TheBreadCat

Reputation: 197

Splitting at space if not between quotes

i tried this:

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

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

Upvotes: 4

Views: 3464

Answers (3)

Bart Kiers
Bart Kiers

Reputation: 170148

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

Upvotes: 17

AabinGunz
AabinGunz

Reputation: 12347

Does this work?

var str="Hi there"
var splitOutput=str.split(" ");

//splitOutput[0]=Hi
//splitOutput[1]=there

Sorry I misunderstood your question add this from Bart's explanation \s(?=([^"]*"[^"]*")*[^"]*$) or [ ]+(?=([^"]*"[^"]*")*[^"]*$)

Upvotes: 0

wjans
wjans

Reputation: 10115

Is this what you are looking for?

input.split("(?<!\") (?!\")")

Upvotes: 0

Related Questions