简体   繁体   English

如何使用Java正则表达式来匹配此模式?

[英]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? 我希望一个模式与句子中的*instance*stuck*相匹配,实例和被卡住之间的单词数可以是1到3。如何在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 “服务器123中xyz处的实例被卡住”将与模式不匹配

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] \\\\w匹配任何字母数字字符,就像[a-zA-Z0-9]
\\\\s is class for spaces \\\\s是空格类
+ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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