I have a user supplied string, that I then need to turn into a Regular Expression where their string is treated as a literal, then I append a pre-written regular expression on the end.
Essentially, a way to say “what the user supplied, followed by this pattern”.
This makes me think I may need to sanitise the user supplied string, to escape meta-characters.
As an example, this is what I tried
\\ Replace "\" with "\\"
String rE = userText.replaceAll("\\", "\\\\");
\\ Replace . with \.
rE = rE.replaceAll(".", "\\.");
However this fails with the following message, when matching the \ escaping
Execution aborted because of unhandled exception:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^ at java.util.regex.Pattern.error(Pattern.java:1725)
at java.util.regex.Pattern.compile(Pattern.java:1478)
Is there an easier way to do this? I suspect there’s a built in method to make potential regEx’s into literals, but I can’t find it.
I’ve had a look through similar questions, but none seem to want to treat the users input string as a literal.
Use
Pattern.quoteMethod to quote the user supplied string as literal pattern.