As of Java 11 one can use Pattern#asMatchPredicate
which returns Predicate<String>
.
String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
boolean match = matchesRegex.test(string); // true
The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate
offers and
, or
and negate
methods.
String string = "stores$store$product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;
boolean match = hasLength.and(matchesRegex).test(string); // false