I am trying to replace a +
character into a hyphen
I have in my string.
String str = "word+word";
str.replaceAll('+ ', '-');
I tried using replace but it throwing an exception
.Is there any other method to do this.
I am trying to replace a +
character into a hyphen
I have in my string.
String str = "word+word";
str.replaceAll('+ ', '-');
I tried using replace but it throwing an exception
.Is there any other method to do this.
Use
A few errors in your code :
+
char must be escaped as the first argument is a regular expression (and\
itself must be escaped in java string literals)The
replaceAll
function takes a regular expression as its first argument. It so happens that+
is a special character in regular expression language. Try replacing+
with\\+
. This will escape the plus sign, thus making the code to treat it like a normal character.Also, the
replaceAll
method yields a string, so that will not work. Try doing:Use "" as opposed to '' in replaceAll.
String java.lang.String.replaceAll(String regex, String replacement)
If you are not sure about the escape sequence you need to use,
You could simply do this.
This will automatically escape the regex predefined tokens to match in a literal way
Just use
replace
:This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your
str
variable becauseString
in Java are immutable. In this case methodreplace
doesn't change currentString
(str
) but create new one with replaced+
to '-'.`replaceAll´ is for regular expressions and strings are immutable. Use:
instead...