Kunal Gupta
Kunal Gupta

Reputation: 41

How to replace a string in java if replacement string contains special(some regex) character

I am trying to replace a string in java where my replacement string contains special character exactly same as shown below.

String s1 = char(1)+"abc"+char(1);
String s2 = "!@#$%^&*()-_`~";
String s3 = s.replaceAll(s1, s2);

Above written code throws java.lang.IllegalArgumentException: Illegal group reference

Upvotes: 0

Views: 1569

Answers (2)

nhahtdh
nhahtdh

Reputation: 56829

String.replace(CharSequence, CharSequence) as suggested in Alexei Levenkov's answer is the way to go if you want to replace a string with another string literally.

For the sake of completeness, if you want to do literal string replacement with replaceAll, you need to quote both the pattern string and the replacement string, so that they are treated literally (i.e. without any special meaning).

inputString.replaceAll(Pattern.quote(pattern), Matcher.quoteReplacement(replacement));

Pattern.quote(String) creates a pattern which matches the specified string literally.

Matcher.quoteReplacement(String) creates a literal replacement string for the specified string.

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

You should use regular replace instead replaceAll that takes regular expression.

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

Sample (http://ideone.com/HbV9eO)

String s= "\u0001abc\u0001more\u0001abc\u0001";
String s1 = "\u0001abc\u0001";
String s2 = "!@#$%^&*()-_`~";
String s3 = s.replace(s1, s2);
System.out.println("new string = " + s3);

Upvotes: 1

Related Questions