Reputation: 9205
I want to replace all occurrences of +- with - from a string called myStr in java. I also want to replace all occurrences of -- with + from myStr. The following two lines of code are not accomplishing this in java:
myStr.replaceAll("\\+-", "-");
myStr.replaceAll("\\--", "+");
Can anyone show me how to alter these two lines of code to accomplish the desired replacements?
I usually try to avoid regular expressions, but am not sure how to do this operation without them.
Upvotes: 0
Views: 122
Reputation: 89241
public static String escapePlusMinus(String myStr) {
Pattern pattern = Pattern.compile("[+-]-");
Matcher matcher = pattern.matcher(myStr);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
if (matcher.group(0).equals("+-")) {
matcher.appendReplacement(result, "-");
}
else {
matcher.appendReplacement(result, "+");
}
}
matcher.appendTail(result);
return result.toString();
}
escapePlusMinus("+-, --, +-, ---+---")
⇒ "-, +, -, +--+"
The last token is matched as:
"--"
⇒ "+"
"-"
skipped, since there are not another "-"
following it."+-"
⇒ "-"
"--"
⇒ "+"
Upvotes: 0
Reputation: 179256
You're throwing out the return value of the function. You probably want to use:
myStr = myStr.replaceAll("\\+-", "-").replaceAll("--", "+");
update with additional info from comment:
Be sure to keep the return value of replaceAll
.
myStr = myStr.replaceAll("\\+-", "-");
and later
myStr = myStr.replaceAll("--", "+");
Upvotes: 5