-2

I have a snippet

public static void main(String[] args) {    
    // replacement text
    String replacement = "Not Set";
    // text
    String text = "Item A \\(XXX\\) Lock"; // text is "Item A\(XXX\)Lock"
    String regex = "\\(XXX\\)"; // regex is "\(XXX\)"
    // result text
    String resultText = text.replaceAll(regex, replacement);
    System.out.println("Result text: " + resultText);
}

resultText is "Item A \(XXX\) Lock" -> I can not replace "\(XXX\)" to "Not Set".

Please help me if you know about this problem.

2 Answers2

1

The regex language has its own escape sequence on top of the Java string literal escape sequence. So to match a backslash, you need \\ in the regex and thus \\\\ in the Java string literal

In this case you could also use Pattern.quote

text.replaceAll(Pattern.quote(regex), Matcher.quoteReplacement(replacement));
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
1

The characters \, ( and ) all have a special meaning when used in a regular expression. But you don't want to use them with their special meaning, which means you have to escape them in the regular expression. That means preceding them with \, to tell the regular expression processor not to invoke the special meaning of those characters.

In other words, a regular expression containing \\ will match \, a regular expression containing

\( will match ( and so on.

To match \(XXX\), the regular expression you want will be \\\(XXX\\\) - see how there's an extra \ for each \, ( and ) that you want to match. But to specify this regular expression in a Java String literal, you need to write \\ in place of each \. That is, you need to write

"\\\\\\(XXX\\\\\\)". There are six \ characters in each little run of them.

String regex = "\\\\\\(XXX\\\\\\)"; 
String resultText = text.replaceAll(regex, replacement);
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110