Avoiding all special regular expression characters, but not all at once (using the .quote () pattern), only one after the other

Here's the problem: the user is provided with a text field into which he can enter a filter. Filter to filter unfiltered data. The user experiencing the brainwashing of Oracle Forms does not emit any special characters except%, which I think more or less means ". *" A regular expression in Java.

If the user-user behaves well, this person will enter material like "CTHULH%", in which case I can build a template:

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

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

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

since it puts \ Q at the beginning and \ E at the end of the line, rendereing my% →. * switch moot.

Question: should I look for every special character in the template code and avoid it myself by adding "\\" in front, or can this be done automatically? Or am I deeply immersed in the problem, am I omitting the obvious way to resolve it?

+5
source share
2 answers

How about Pattern.compile(Pattern.quote(inputText).replaceAll("%", "\\E.*\\Q"));?

This will result in the following pattern:

input:   ".+\[a-#$%^&*(" 
quote:   \Q".+\[a-#$%^&*("\E 
replace: \Q".+\[a-#$\E.*\Q^&*("\E

% , \Q\E ( %, \Q\E.*\Q\E), .

Update:

replace(...) replaceAll(...): , . , , Pattern.compile(Pattern.quote(inputText).replaceAll("%", "\\\\E.*\\\\Q")); ( ).

String#replaceAll(...):

, , , .

+2

, :

  • %
  • Pattern.quote
  • , .*
+6

All Articles