Replace all instances of a sequence in java

I want to replace all instance like

{IMAGE:imagename} with imagepath ,

{MESSAGE:messagename} with message.

I tried using replaceAll function of string class but not able to achieve the same.

Example code :

String str = "HELLO WORLD {IMAGE:abcd}";
str = str.replaceAll("{IMAGE:abcd}", "defg");

Output :

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{IMAGE:abcd}
    at java.util.regex.Pattern.error(Pattern.java:1713)
    at java.util.regex.Pattern.closure(Pattern.java:2775)
    at java.util.regex.Pattern.sequence(Pattern.java:1889)
    at java.util.regex.Pattern.expr(Pattern.java:1752)
    at java.util.regex.Pattern.compile(Pattern.java:1460)
    at java.util.regex.Pattern.<init>(Pattern.java:1133)
    at java.util.regex.Pattern.compile(Pattern.java:823)
    at java.lang.String.replaceAll(String.java:2189)
    at com.example.WorkSheet.main(WorkSheet.java:28)

Answers


{ is a regex metacharacter and should be escaped, try this

str = str.replaceAll("\\{IMAGE:abcd}", "defg");

note that it is enough to escape {, regex compiler will understand that } is used as a regular character.


Need Your Help

Why don't I have to release managedObjectContext in the 2nd TableViewController

iphone cocoa-touch core-data memory-leaks release-management

I have two tableview controllers showing CoreData objects. One is a detail view (with sentences) one is an overview (with stories).

Yii url with server static IP address

php url yii

I'm developping with Yii, and I need to send mail to contacts with an link. The proble is that the code