How to escape all regex special chars but not all at once (by Pattern.quote()), just one-by one
java, regex
Solution
What about `Pattern.compile(Pattern.quote(inputText).replaceAll("%", "\\E.*\\Q"));`?
This should result in the following pattern:
input: ".+\[a-#$%^&*("
quote: \Q".+\[a-#$%^&*("\E
replace: \Q".+\[a-#$\E.*\Q^&*("\E
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(...)` and `replaceAll(...)`: 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 call `Pattern.compile(Pattern.quote(inputText).replaceAll("%", "\\\\E.*\\\\Q"));` (quote the backslashes in the string and in the expression).
From the documentation on `String#replaceAll(...)`:
Note that backslashes in the replacement string may cause the results to be different than if it were being treated as a literal replacement string.
Problem
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?