Kevin
Kevin

Reputation: 2291

How to use Java regex to match this pattern?

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:

  1. "The instance stuck" will match the pattern
  2. "The instance just got stuck" will match the pattern
  3. "The instance in the server 123 at xyz is stuck" will NOT match the pattern

Upvotes: 0

Views: 1418

Answers (4)

Pshemo
Pshemo

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

Wug
Wug

Reputation: 13196

Perhaps:

instance (\w* ){0,3}stuck

This will also match wacky whitespace:

instance\s*(\w*\s*){0,3}stuck

Upvotes: 0

godspeedlee
godspeedlee

Reputation: 672

try with this: instance( \w+){1,3} stuck

Upvotes: 0

maxko87
maxko87

Reputation: 2940

Something like this:

instance(\\w\\s){1,3}stuck

Look here for more details about limiting repetitions of words.

Upvotes: 0

Related Questions