helfo helfo - 4 months ago 32x
Java Question

Convert RegEx from JavaScript to Java

OK, so I am trying to split a String by ", " which are not inside '[' or ']'. I have a working RegEx for JavaScript but have been unable to convert it to Java syntax.



Example sentence:

ex1 , [ex2 , ex3 ] , ex 4 , ex 4, [ex , ex ]

It works fine on http://refiddle.com but when I try and use the RegEx in Java (under Eclipse) I get an error saying:

Unclosed character class near index 10

All I did was remove the '/' at the beginning and the "/g" at the end and I have been unable to translate the Syntax.

What would be the best way to achieve this?


In Java character classes, ] and [ must be escaped, unlike in JavaScript where you only have to escape ] symbol (inside the character class).

String pat = ",(?![^\\[]*])";

Here is an IDEONE demo:

String s = "ex1 , [ex2 , ex3 ] , ex 4 , ex 4, [ex , ex ]";
String pat = ",(?![^\\[]*])";
String[] result = s.split(pat);

Note that neither in Java, nor in JS, the ], outside the character class, does not have to be escaped.