简体   繁体   中英

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

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.

Something like this:

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

Look here for more details about limiting repetitions of words.

试试这个: instance( \\w+){1,3} stuck

Perhaps:

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

This will also match wacky whitespace:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM