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

后端 未结 8 1794
别跟我提以往
别跟我提以往 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条回答
  • 2020-12-28 12:37

    You need to escape the + for the regular expression, using \.

    However, Java uses a String parameter to construct regular expressions, which uses \ for its own escape sequences. So you have to escape the \ itself:

    "\\+"
    
    0 讨论(0)
  • 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

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