Thumbz
Thumbz

Reputation: 347

Using replaceAll with Strings containing special characters in Java

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.

Upvotes: 1

Views: 9659

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200148

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", "");

Upvotes: 1

Eugene
Eugene

Reputation: 120848

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","");

Upvotes: 1

Stephen C
Stephen C

Reputation: 718758

... 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 ...

Upvotes: 4

Related Questions