Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape all regex special chars but not all at once (by Pattern.quote()), just one-by one

Tags:

java

regex

Here's the problem: user is presented with a text field, unto which may he or she type the filter. A filter, to filter unfiltered data. User, experiencing an Oracle Forms brainwashing, excpets no special characters other than %, which I guess more or less stands for ".*" regex in Java.

If the User Person is well behaved, given person will type stuff like "CTHULH%", in which case I may construct a pattern:

Pattern.compile(inputText.replaceAll("%", ".*"));

But if the User Person hails from Innsmouth, insurmountably will he type ".+\[a-#$%^&*(" destroying my scheme with a few simple keystrokes. This will not work:

Pattern.compile(Pattern.quote(inputText).replaceAll("%", ".*"));

as it will put \Q at the beginning and \E at the end of the String, rendereing my % -> .* switch moot.

The question is: do I have to look up every special character in the Pattern code and escape it myself by adding "\\" in front, or can this be done automagically? Or am I so deep into the problem, I'm omitting some obvious way of resolution?

like image 438
pafau k. Avatar asked May 09 '12 15:05

pafau k.


People also ask

How do I allow only special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

How do you escape a character in regex Java?

Characters can be escaped in Java Regex in two ways which are listed as follows which we will be discussing upto depth: Using \Q and \E for escaping. Using backslash(\\) for escaping.

Why do we need to escape special characters?

When a text string contains characters that have a special functionality (%, *, +, .), the characters should be "escaped" with a backslash ( \ ). For instance, %, *, +, .). In this way, the characters will be interpreted literally, and not with their special meaning.


1 Answers

I think this algorithm should work for you:

  • Split on %
  • Quote each part separately using Pattern.quote
  • Join the string using .*
like image 112
Mark Byers Avatar answered Oct 03 '22 07:10

Mark Byers