简体   繁体   中英

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.

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.

As others already said, { is a special character used in the pattern ( } too). You have to escape it to avoid any confusion.

Escaping those manually can be dangerous (you might omit one and make your pattern go completely wrong) and tedious (if you have a lot of special characters). The best way to deal with this is to use Pattern.quote()


Related issues:

Resources:

replaceAll() takes a regular expression as a parameter, and { is a special character in regular expressions. In order for the regex to treat it as a regular character, it must be escaped by a \\ , which must be escaped again by another \\ in order for Java to accept it. So you must use \\\\{ .

You can remove the curly brackets with .replaceAll() in a line with square brackets

String newString = originalString.replaceAll("[{}]", "X")

eg: newString = "ARG:token_name"

if you want to further separate newString to key and value, you can use .split()

String[] arrayString = newString.split(":")

With arrayString, you can use it for your HashMap with .put() , arrayString[0] and arrayString[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM