How to use regex in String.contains() method in Java


String.contains works with String, period. It doesn’t work with regex. It will check whether the exact String specified appear in the current String or not.

Note that String.contains does not check for word boundary; it simply checks for substring.

Regex solution

Regex is more powerful than String.contains, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.

Use String.matches with the following regex:


The RAW regex (remove the escaping done in string literal – this is what you get when you print out the string above):


The \b checks for word boundary, so that you don’t get a match for restores store products. Note that stores 3store_product is also rejected, since digit and _ are considered part of a word, but I doubt this case appear in natural text.

Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product will not match the regex above, since you are searching for the word store without s.

. normally match any character except a number of new line characters. (?s) at the beginning makes . matches any character without exception (thanks to Tim Pietzcker for pointing this out).

Leave a Comment