[英]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: 例如:
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. +
意味着元素之前+
必须找到至少一次。
试试这个: 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.