Search code examples
javaregexstringcontains

Java String#contains() using String#matches() with escape character


I need a simple way to implement the contains function using matches. I believe this is my starting point:

xxx.matches("'.*yyy.*'");

But I need to make it a universal method and pre-process whatever I search for to be accepted by matches! This must be done using only the escape '\' character!

Imagine a string SEARCH_FOR that can contain some special characters that must be "regex escaped"...

String SEARCH_FOR="*.\\"
xxx.matches("'.*" + SEARCH_FOR + ".*'");

Are there any catches? Special situations? Any other "special chars should be taken into account?


Solution

  • Are you looking for Pattern.quote(String) ?

    This escapes special characters for you.


    EDIT:

    After reading the comments, I really hope you try Pattern.quote(yourString.toLowerCase()) as it sounds like you've been using Pattern.quote(yourString).toLowerCase(). If DataNucleus is applying the regex then there should be no problems with using the \Q and \E escape sequence.

    Since you have really asked for it, ".\\".replaceAll("(\\.|\\$|\\+|\\*|\\\\)", "\\\\\$1") outputs \.\\ This will escape .'s, $'s, + 's, *'s and \'s. Note that the security of this is now all upon you. If you don't escape something you needed to, or you escape it incorrectly, you will either allow people to use regex inside the search term when you weren't expecting to or it won't returns results that you were expecting.