Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing literal character in regex

Tags:

java

regex

I have the following string

\Qpipe,name=office1\E

And I am using a simplified regex library that doesn't support the \Q and \E.

I tried removing 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?

like image 578
Shervin Asgari Avatar asked Mar 15 '11 15:03

Shervin Asgari


3 Answers

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

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

Alternatively and a simpler way would be to use the replace method which takes string and not regex:

s.replace("\\Q", "").replace("\\E", "")
like image 182
codaddict Avatar answered Oct 02 '22 14:10

codaddict


Use the Pattern.quote() function to escape special characters in regex for example

s.replaceAll(Pattern.quote("\Q"), "")
like image 29
desw Avatar answered Oct 02 '22 15:10

desw


replaceAll takes 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 regex characters for your simplified regex library.

like image 33
Mike Samuel Avatar answered Oct 02 '22 16:10

Mike Samuel