Shahensha Khan Shahensha Khan - 4 months ago 18
Java Question

Regex throwing exception in JAVA, working in PHP

i have a working PHP regex which is

\w+[\(](\?*)\w+[\,](\?*)\w+[\)]


the link for its working is provided here https://regex101.com/r/tB2pS3/1

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

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:

(?<A>
  \w+\(
  \?*\w+
  (?:,\?*\w+)?
  \)
)
(,
  \w+\(
  \?*\w+
  (?:,\?*\w+)?
  \)
)*

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()) {
        System.out.println(m.group(0));
    }
}

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

Comments