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
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:
"\\+"
Others have already stated the correct method of:
+
as \\+
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