4

i tried this:

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

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

Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
TheBreadCat
  • 197
  • 1
  • 4
  • 11
  • I've answered (almost) the same question here: http://stackoverflow.com/questions/3147836/c-regex-split-commas-outside-quotes Its for C# there, but the solution should work for java. – Jens May 10 '11 at 07:30

3 Answers3

17

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
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
0

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 [ ]+(?=([^"]*"[^"]*")*[^"]*$)

AabinGunz
  • 12,109
  • 54
  • 146
  • 218
0

Is this what you are looking for?

input.split("(?<!\") (?!\")")
wjans
  • 10,009
  • 5
  • 32
  • 43