0

I try to use Matcher.quoteReplacement, but I find it can escape $ but do not escape |. So I try to use the other method StringEscapeUtils.escapeJava, but it do not escape {. So I can only write a method like this. Does any java class already have this method?

String sampleStr="$abc.|{@#$abc";
String splitStr="{@#$"; 
System.out.println(Matcher.quoteReplacement(splitStr));
System.out.println(StringEscapeUtils.escapeJava(splitStr));
System.out.println(splitStr.replace("\\", "\\\\")
         .replace("*", "\\*")
         .replace("+", "\\+").replace("|", "\\|")
         .replace("{", "\\{").replace("}", "\\}")
         .replace("(", "\\(").replace(")", "\\)")
         .replace("^", "\\^").replace("$", "\\$")
         .replace("[", "\\[").replace("]", "\\]")
         .replace("?", "\\?").replace(",", "\\,")
         .replace(".", "\\.").replace("&", "\\&")); 

/* have exception when the split String contains "{"}
System.out.println(sampleStr.split(Matcher.quoteReplacement(splitStr)).length);
System.out.println(sampleStr.split(StringEscapeUtils.escapeJava(splitStr)).length);*/
System.out.println(sampleStr.split(splitStr.replace("\\", "\\\\")
         .replace("*", "\\*")
         .replace("+", "\\+").replace("|", "\\|")
         .replace("{", "\\{").replace("}", "\\}")
         .replace("(", "\\(").replace(")", "\\)")
         .replace("^", "\\^").replace("$", "\\$")
         .replace("[", "\\[").replace("]", "\\]")
         .replace("?", "\\?").replace(",", "\\,")
         .replace(".", "\\.").replace("&", "\\&")).length);
Holger
  • 285,553
  • 42
  • 434
  • 765
flower
  • 2,212
  • 3
  • 29
  • 44

1 Answers1

2

The method Matcher.quoteReplacement is, as the name suggests, for quoting a replacement string. When you want to quote a pattern string, you have to use Pattern.quote.

String sampleStr="$abc.|{@#$abc";
String splitStr="{@#$";
for(String s: sampleStr.split(Pattern.quote(splitStr)))
    System.out.println(s);
$abc.|
abc

Note that instead of converting a string to a quoted string, to let the regex engine convert it back to the literal string when parsing, you can tell the engine directly that you want to perform a literal match:

for(String s: Pattern.compile(splitStr, Pattern.LITERAL).split(sampleStr))
    System.out.println(s);

It’s a bit more to write but more efficient. Further, it works with arbitrary CharSequence inputs, not only with String.

Holger
  • 285,553
  • 42
  • 434
  • 765