1

I am matching a pattern which is a string "test" in sentence "you are test" and replace it with "test\".

StringBuffer sb = new StringBuffer();
Pattern pattern = Pattern.compile("test", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("you are test");
while (matcher.find()) {
matcher.appendReplacement(sb, "test\"));
            }
matcher.appendTail(sb);
replacementString = sb.toString();

The issue is in the statement matcher.appendReplacement(sb, "test\")); where "\" is considered as special character and replacement is not performed.

Please share your thoughts on how overcome this scenario and how to replace with a "\" in the string.

1
  • 2
    try following? matcher.appendReplacement(sb, "<test\\>")); Commented Feb 15, 2013 at 13:27

2 Answers 2

6

To put a \ in a string literal in java, you have to escape it as \\.

But it's a little more complicated. See the javadoc :

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

So you have to double-escape :

matcher.appendReplacement(sb, "test\\\\"));
Sign up to request clarification or add additional context in comments.

Comments

0

Why are you using all those lines of code, when one line will do the same thing:

String s = input.replaceAll("test", "$0\\\\");

Note the use of $0 to back-reference the whole match, and the double-double backslash to create a literal regex backslash.

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.