Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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.

like image 349
John Topley Avatar asked Mar 04 '09 12:03

John Topley


People also ask

How do you replace a specific character in a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

What does replaceAll \\ s+ do?

\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.

What is the difference between Replace () and replaceAll ()?

The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.

Does replaceAll replace string?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.


Video Answer


1 Answers

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:

"\\+" 
like image 76
toolkit Avatar answered Sep 19 '22 17:09

toolkit