Reputation: 2291
I want a pattern to match *instance*stuck*
in a sentence, the number of words between instance and stuck can be 1 to 3. How can I write this pattern with regular expression in Java?
For example:
Upvotes: 0
Views: 1418
Reputation: 124215
You can try to test it this way
String s1 = "The instance just got stuck";
String s2 = "The instance in the server 123 at xyz is stuck";
System.out.println(s1.matches(".*instance (\\w+\\s+){1,3}stuck.*")); // true
System.out.println(s2.matches(".*instance (\\w+\\s+){1,3}stuck.*")); // false
\\w
matches any alphanumeric character, it is like [a-zA-Z0-9]
\\s
is class for spaces
+
mean that element before +
must be found at least one time.
Upvotes: 4
Reputation: 13196
Perhaps:
instance (\w* ){0,3}stuck
This will also match wacky whitespace:
instance\s*(\w*\s*){0,3}stuck
Upvotes: 0