0

Possible Duplicate:
java String.replaceAll without regex

I have a string and I need to replace some parts of it.
The replacement text contains regex wild chars though. Example:

String target = "Something * to do in ('AAA', 'BBB')";    
String replacement = "Hello";    
String originalText = "ABCDEFHGIJKLMN" + target + "ABCDEFHGIJKLMN";  
System.out.println(originalText.replaceAll(target, replacement));    

I get:
ABCDEFHGIJKLMNSomething * to do in ('AAA', 'BBB')ABCDEFHGIJKLMN

Why doesn't the replacement occur?

Community
  • 1
  • 1
Jim
  • 18,826
  • 34
  • 135
  • 254

2 Answers2

3

Because *, ( and ) are all meta-characters in regular expressions. Hence all of them need to be escaped. It looks like Java has a convenient method for this:

java.util.regex.Pattern.quote(target)

However, the better option might be, to just not use the regex-using replaceAll function but simply replace. Then you do not need to escape anything.

Community
  • 1
  • 1
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
  • Using `quote` I get: `ABCDEFHGIJKLMN\QHello\EABCDEFHGIJKLMN`. How can I get rid of `Q`? – Jim Nov 07 '12 at 12:54
  • @Jim.. No you shouldn't get that. It should work fine. How have you used it? – Rohit Jain Nov 07 '12 at 12:57
  • I did: `target = Pattern.quote(target); target = Pattern.quote(target); String replacement = "Hello"; String originalText = "ABCDEFHGIJKLMN" + target + "ABCDEFHGIJKLMN"; System.out.println(originalText.replaceAll(target, replacement));` – Jim Nov 07 '12 at 13:14
  • @Jim this also puts the escaped target in your initial string. of course you only need to escape it when you use it as a regex. leave `target` as it is, and feed `replaceAll` with the snippet from my answer. or use `replace` anyway. – Martin Ender Nov 07 '12 at 13:16
  • because you do this twice `target = Pattern.quote(target);`, do it once and it will work like @m.buettner says. – jlordo Nov 07 '12 at 13:21
2

String.replaceAll() takes a regular expression and so it's trying to expand these metacharacters.

One approach is to escape these chars (e.g. \*).

Another would be to do the replacement yourself by using String.indexOf() and finding the start of the contained string. indexOf() doesn't take a regexp but rather a normal string.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440