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.
This means it tries to match as few times as possible, instead of trying to match as many times as possible.
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 .
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).
Should be:
result.replaceFirst("\\+", "011")
or, alternatively:
result.replaceFirst(Pattern.quote("+"), "011")
\+
is not a valid string escape sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With