Why does this exception occur when trying to match this regular expression in Java?

I am trying to match a specific string from an HTML document and have this regex pattern to capture it:

Pattern somePattern = Pattern.compile("var json = ({\"r\":\"^d1\".*});");

However, when I try to use this code at runtime, I get this error:

FATAL EXCEPTION: Timer-0
 java.util.regex.PatternSyntaxException: Syntax error U_REGEX_RULE_SYNTAX near index 13:
 var json = ({"r":"^d1".*});
              ^
     at com.ibm.icu4jni.regex.NativeRegEx.open(Native Method)
     at java.util.regex.Pattern.compileImpl(Pattern.java:383)
     at java.util.regex.Pattern.<init>(Pattern.java:341)
     at java.util.regex.Pattern.compile(Pattern.java:317)

Can anyone tell me what I'm doing wrong?

+3
source share
1 answer

It seems to me that you need to escape the characters "{}", as they mean something special for regular expression.

This is a long way of expressing "count", therefore it .{0,}is .* .{0,1}equivalent to equivalent .?, and .{2,4}means at least two, but not more than four previous matches

+4

Source: https://habr.com/ru/post/1747110/


All Articles