Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java regex match Plus sign

I I want to match the plus sign in a string and replace it, but when I do

result.replaceFirst("\+", "011")

it complains that \+ is not valid.

like image 499
Johnny Avatar asked Aug 23 '11 14:08

Johnny


People also ask

What does +? Mean in regex?

This means it tries to match as few times as possible, instead of trying to match as many times as possible.

What is plus in regex Java?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .

How do I add symbols in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

Should be:

result.replaceFirst("\\+", "011")

or, alternatively:

result.replaceFirst(Pattern.quote("+"), "011")

\+ is not a valid string escape sequence.

like image 171
MByD Avatar answered Oct 22 '22 11:10

MByD