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.
views:
4853answers:
4
+6
A:
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);
Kris
2009-03-04 12:35:18
+5
A:
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:
"\\+"
toolkit
2009-03-04 12:36:32
I have the bad habit of using '/'s when building the regex and then running .replace('/', '\\'), so that I don't have to type "\\\\" to match a literal backslash.
Aaron Maenpaa
2009-03-04 12:49:49
If you want to replace a fixed string, Pattern.quote(String) is a very nice friend.
gustafc
2009-03-04 13:06:23
+6
A:
when in doubt, let java do the work for you:
myStr.replaceAll(Pattern.quote("+"), replaceStr);
james
2009-03-04 16:43:58
+1
A:
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");
Simon Nickerson
2009-03-19 08:28:53
thx for pointing to this. helped me remembering using this non-regex solution in simple cases.
Gerhard Dinhof
2010-01-14 08:00:30
isn't that equivalent to using mystr.replace("+", "plus") ? replace does not use regex (while replaceAll does).
Vinze
2010-06-08 10:16:39