I want to check if a String contains the words "stores", "store", and "product" in that order, no matter what is in between them.
I tried using someString.contains(stores%store%product);
and also .contains("stores%store%product");
Do I need to explicitly declare a regex and pass it on the method or can I not pass a regex at all?
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.
matcher.find()
does what you needed. Example:
Pattern.compile("stores.*store.*product").matcher(someString).find();
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
You can simply use matches
method of String class.
boolean result = someString.matches("stores.*store.*product.*");
public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();
return Pattern.compile(pattern).matcher(text).find();
}
1.result: true
2.result: true
Source: Stackoverflow.com