0

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.