How to replace a plus character using Java's String.replaceAll method

后端 未结 8 1888
别跟我提以往
别跟我提以往 2020-12-28 11:50

What\'s the correct regex for a plus character (+) as the first argument (i.e. the string to replace) to Java\'s replaceAll method in the String class? I can\'t

8条回答
  •  萌比男神i
    2020-12-28 12:38

    Others have already stated the correct method of:

    1. Escaping the + as \\+
    2. Using the Pattern.quote method which escapes all the regex meta-characters.

    Another method that you can use is to put the + in a character class. Many of the regex meta characters (., *, + among many others) are treated literally in the character class.

    So you can also do:

    orgStr.replaceAll("[+]",replaceStr);
    

    Ideone Link

提交回复
热议问题