0

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
0

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. This is exactly what I am looking for. Would you please explain how does the (\\w+\\s+) work? Thanks.
You're using java, so you must escape backslashes, which is why they are doubled. \w will match any word character, and \s will match any whitespace character.
how about the "+"? zero or more? 1 or more?
+ mean 1 or more time (it is shorter version of {1,} just like * mean {0,})
0

Something like this:

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

Look here for more details about limiting repetitions of words.

2 Comments

\\w will only match one word character.
Thanks. But what do you mean one word character?
0

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

Comments

0

Perhaps:

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

This will also match wacky whitespace:

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

1 Comment

Wrap with \b's to force matching only whole words instance and stuck, otherwise it will match things like "instance stuckified"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.