Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace brackets in strings

I have a list of strings that contains tokens.
Token is:

{ARG:token_name}.

I also have hash map of tokens, where key is the token and value is the value I want to substitute the token with.

When I use "replaceAll" method I get error:

java.util.regex.PatternSyntaxException: Illegal repetition

My code is something like this:

myStr.replaceAll(valueFromHashMap , "X"); 

and valueFromHashMap contains { and }.

I get this hashmap as a parameter.

like image 850
omrid Avatar asked Jan 17 '26 03:01

omrid


1 Answers

String.replaceAll() works on regexps. {n,m} is usually repetition in regexps.

Try to use \\{ and \\} if you want to match literal brackets.

So replacing all opening brackets by X works that way:

myString.replaceAll("\\{", "X");

See here to read about regular expressions (regexps) and why { and } are special characters that have to be escaped when using regexps.

like image 67
Johannes Weiss Avatar answered Jan 19 '26 19:01

Johannes Weiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!