Question

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)
...
Was it helpful?

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?

OTHER TIPS

"\\\"example\\\"(.+?)}"

should work. Your string will be converted to a pattern, which means it will process the escape chars twice. so you need to type \\ for \ and \" for " .

Here is the example http://www.myregextester.com/?r=ab9d1f06

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top