Home > front end >  Java String.split() is splitting unexpectedly on a given regex
Java String.split() is splitting unexpectedly on a given regex

Time:12-08

I am trying to use String.split() on a string to split on a given regex and I am not getting the expected results. I have tested my pattern and it seems to be a valid regex.

String pattern = "/AND|OR/g";
String myString = "(foo=bar)AND(fizz=buzz)"
String[] myArr = myString.split(pattern);

Expected result:

[(foo=bar),(fizz=buzz)]

Result

[(foo=bar)AND(fizz=buzz)]

CodePudding user response:

"/AND|OR/g"; will match "/AND" or it will match "OR/g". Neither string exists in your input, so no splitting is performed.

If you are trying to split on "AND" or "OR", use the pattern "AND|OR".

CodePudding user response:

The pattern /AND|OR/g looks to be JavaScript syntax, not Java. In Java, we do not need to place delimiters around the pattern, and also String#split() defaults to being global. Putting this all together, we can use:

String pattern = "AND|OR";
String myString = "(foo=bar)AND(fizz=buzz)";
String[] myArr = myString.split(pattern);
System.out.println(Arrays.toString(myArr));  // [(foo=bar), (fizz=buzz)]
  • Related