How to use regex in String.contains() method in Java
String.contains
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:
"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"
The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):
(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*
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).
matcher.find()
does what you needed. Example:
Pattern.compile("stores.*store.*product").matcher(someString).find();
You can simply use matches
method of String class.
boolean result = someString.matches("stores.*store.*product.*");
If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -
private static final validPattern = "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
Pattern pattern = Pattern.compile(validPattern);
Matcher matcher = pattern.matcher(inputString);
System.out.print(matcher.find()); // should print true or false.
Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.