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?
What about
Pattern.compile(Pattern.quote(inputText).replaceAll("%", "\\E.*\\Q"));?This should result in the following pattern:
In case the
%character was the first or last character you would get a\Q\E(if you only have the input%the expression would end up being\Q\E.*\Q\E) but this should still be a valid expression.Update:
I forgot the difference between
replace(...)andreplaceAll(...): the replacement parameter in the former is a literal while the replacement in the latter is an expression itself. Thus – as you already stated in your comment – you need to callPattern.compile(Pattern.quote(inputText).replaceAll("%", "\\\\E.*\\\\Q"));(quote the backslashes in the string and in the expression).From the documentation on
String#replaceAll(...):