Search code examples
javaregexstringescaping

Escaping a String from getting regex parsed in Java


In Java, suppose I have a String variable S, and I want to search for it inside of another String T, like so:

   if (T.matches(S)) ...

(note: the above line was T.contains() until a few posts pointed out that that method does not use regexes. My bad.)

But now suppose S may have unsavory characters in it. For instance, let S = "[hi". The left square bracket is going to cause the regex to fail. Is there a function I can call to escape S so that this doesn't happen? In this particular case, I would like it to be transformed to "\[hi".


Solution

  • String.contains does not use regex, so there isn't a problem in this case.

    Where a regex is required, rather rejecting strings with regex special characters, use java.util.regex.Pattern.quote to escape them.