Search code examples
javaandroidregexreplaceallpatternsyntaxexception

Regex pattern SyntaxException


In my app, I'd like to remove all text in between "example" and the first occurance after this of } from a string. And I want to do this for all occurences. So I use this code:

myString.replaceAll("\"example\"(.+?)}", "");

However, this gives me a PatternSyntaxException. Why? And: how do I solve it?

stack trace:

05-10 23:32:16.129: W/System.err(724): java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 16:
05-10 23:32:16.129: W/System.err(724): "example"(.+?)}
05-10 23:32:16.129: W/System.err(724):                 ^
05-10 23:32:16.159: W/System.err(724):  at java.util.regex.Pattern.compileImpl(Native Method)
05-10 23:32:16.190: W/System.err(724):  at java.util.regex.Pattern.compile(Pattern.java:400)
05-10 23:32:16.190: W/System.err(724):  at java.util.regex.Pattern.<init>(Pattern.java:383)
05-10 23:32:16.219: W/System.err(724):  at java.util.regex.Pattern.compile(Pattern.java:374)
05-10 23:32:16.219: W/System.err(724):  at java.lang.String.replaceAll(String.java:1784)
...

Solution

  • OK, so I don't understand why this gave an exception, but it seems that what you need to do is escape the last curly brace. So instead of

    myString.replaceAll("\"example\"(.+?)}", "");
    

    you do

    myString.replaceAll("\"example\"(.+?)\\}", "");
                                         ^^
    

    The first string worked for me in Java 1.7.0_51 and 1.8.0_05, so I'm not sure how this came about... But it works?