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

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:

"\\+"

when in doubt, let java do the work for you:

myStr.replaceAll(Pattern.quote("+"), replaceStr);

You'll need to escape the + with a \ and because \ is itself a special character in Java strings you'll need to escape it with another \.

So your regex string will be defined as "\\+" in Java code.

I.e. this example:

String test = "ABCD+EFGH";
test = test.replaceAll("\\+", "-");
System.out.println(test);

Tags:

Java

Regex