Deleting a literal character in a regular expression

I have the following line

\Qpipe,name=office1\E

And I use a simplified regular expression library that does not support \Q and \E

I tried to remove them

  s.replaceAll("\\Q", "").replaceAll("\\E", "") 

However, I get the error Caused by: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1 \E ^

Any ideas?

+4
source share
4 answers

\ is a special escape character in both the Java string and the regex engine. To pass the literal \ to the regex engine, you must have \\\\ in the Java string. So try:

 s.replaceAll("\\\\Q", "").replaceAll("\\\\E", "") 

An alternative and simpler way would be to use the replace method, which takes a string, not a regular expression:

 s.replace("\\Q", "").replace("\\E", "") 
+11
source

Use the Pattern.quote () function to call special characters in a regular expression, for example

 s.replaceAll(Pattern.quote("\Q"), "") 
+2
source

replaceAll accepts a regular expression string. Instead, just use replace , which takes a literal string. So myRegexString.replace("\\Q", "").replace("\\E", "") .

But that still leaves you with the problem of quoting special regular expression characters for your simplified regular expression library.

+1
source

String.replaceAll () takes a regex as a parameter, so you need to avoid double slash:

 s.replaceAll("\\\Q", "").replaceAll("\\\\E", ""); 
0
source

Source: https://habr.com/ru/post/1343796/


All Articles