1

Basically, this is what I'm trying to do is this:

String s = "to+go+la";

s.replaceAll("to+go", "");

which should return "+la"

I know that if I were to just replace the + signs, I would use \\+, but I'm not sure what I what to do when the signs are embeded. Is the best answer to just remove them from both? This will work for my purposes, but it seems like a duct tape answer.

2
  • 1
    what do you mean by embedded? Can you provide an example? Commented Aug 19, 2012 at 7:36
  • as in, the plus sign is in the middle of "to+go" Commented Aug 19, 2012 at 7:40

3 Answers 3

4

... but it seems like a duct tape answer.

It seems like a "duct tape" answer because you haven't learned why you need to use \+ when you are replacing just a "+" character.

The answer is that "+" is a regex metacharacter. It means "the character or group before this may appear one or more times".


If you want "to+go" to be treated as a literal String (rather than a regex), then one way to do this is to "regex quote" it; e.g.

s.replaceAll(Pattern.quote("to+go"), "");

On the other hand, if the + characters are entirely irrelevant, then removing them would also work ...

Sign up to request clarification or add additional context in comments.

2 Comments

No, I mean removing the plus signs out of both before trying to remove one from the other. It works for me because I plan on taking out the plus signs eventually, but if I didn't, it would be an issue.
Thank you. This is the exact answer I was looking for.
1

Your case doesn't call for a regex, so it is inappropriate to use it. It's both slower and more cumbersome. Use a plain and simple replace instead of replaceAll and you won't need to escape anything:

String s = "to+go+la".replace("to+go", "");

Comments

1

How about this:

  String input = "to+go+la";
  String result = input.replaceAll("to\\+go","");
  System.out.println(result);

Why is this a bad pattern? Do you by embedded mean something like this?

 String input = "to+++go+la";

If so then the only thing that will change is the pattern:

 String result = input.replaceAll("to(\\+)+go","");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.