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

JavaRegex

Java Problem Overview


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 get the syntax right.

Java Solutions


Solution 1 - Java

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:

"\\+"

Solution 2 - Java

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

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

Solution 3 - Java

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);

Solution 4 - Java

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

Solution 5 - Java

If you want a simple string find-and-replace (i.e. you don't need regex), it may be simpler to use the StringUtils from Apache Commons, which would allow you to write:

mystr = StringUtils.replace(mystr, "+", "plus");

Solution 6 - Java

Say you want to replace - with \\\-, use:

 text.replaceAll("-", "\\\\\\\\-");

Solution 7 - Java

String str="Hello+Hello";	
str=str.replaceAll("\\+","-");
System.out.println(str);

OR

String str="Hello+Hello";	
str=str.replace(Pattern.quote(str),"_");
System.out.println(str);

Solution 8 - Java

How about replacing multiple ‘+’ with an undefined amount of repeats?

Example: test+test+test+1234

(+) or [+] seem to pick on a single literal character but on repeats.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn TopleyView Question on Stackoverflow
Solution 1 - JavatoolkitView Answer on Stackoverflow
Solution 2 - JavajamesView Answer on Stackoverflow
Solution 3 - JavaKrisView Answer on Stackoverflow
Solution 4 - JavacodaddictView Answer on Stackoverflow
Solution 5 - JavaSimon NickersonView Answer on Stackoverflow
Solution 6 - JavaRamnathView Answer on Stackoverflow
Solution 7 - JavaJDGuideView Answer on Stackoverflow
Solution 8 - JavaJayView Answer on Stackoverflow