Shahensha Khan Shahensha Khan - 1 year ago 111
Java Question

Regex throwing exception in JAVA, working in PHP

i have a working PHP regex which is


the link for its working is provided here

i am able to use it in PHP as intended but when i use the same in JAVA, it gives me exception that

Exception in thread "main" java.util.regex.PatternSyntaxException: Unknown inline modifier near index 37 (?<A>\w+\((\?*)\w+(,(\?*)\w+)?\))(,(?&A))*

i am not well versed in regex and java, but what i got is that there maybe some support issue after reading some related question on internet, as the regex is working fine and it gives accurate result in PHP, the problem is in JAVA some where.

help is needed in this regard.

Answer Source

Java regex does not support recursion and subroutine calls, (?&A) is invalid here. Also, do not forget to use double backslashes to escape regex metacharacters in Java string literals.

The only wayout is to repeat the (?<A>) group pattern at the end, see this demo:


I'd suggest a block-building method here, when you define the block first, and then build a dynamic pattern:

String block = "\\w+\\(\\?*\\w+(?:,\\?*\\w+)?\\)";
String pat = "(" + block + ")(," + block + ")*";
List<String> strs = Arrays.asList("a(b)", "a(?v)", "a(b),c(?c,a)");
for (String str : strs) {
    Matcher m = Pattern.compile(pat).matcher(str);
    while (m.find()) {

See the Java demo. I removed the inner capturing groups since most probably you are not going to use them anyway.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download