How to replace brackets in strings

前端 未结 4 471
孤城傲影
孤城傲影 2021-01-14 22:44

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

{ARG:token_name}.

I also have hash map of tokens, where key is th

相关标签:
4条回答
  • 2021-01-14 23:37

    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:

    • How to escape a square bracket for Pattern compilation
    • How to escape text for regular expression in Java

    Resources:

    • Oracle.com - JavaSE tutorial - Regular Expressions
    0 讨论(0)
  • 2021-01-14 23:40

    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.

    0 讨论(0)
  • 2021-01-14 23:42

    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]

    0 讨论(0)
  • 2021-01-14 23:44

    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 \\{.

    0 讨论(0)
提交回复
热议问题