我想要一个模式来匹配句子中的*instance*stuck*
,instance和stuck之间的单词数可以是1到3。我如何在Java中用正则表达式编写这个模式?
例如:
- “实例卡住”将与模式匹配
- “实例刚刚卡住”将与模式匹配
- “位于 xyz 的服务器 123 中的实例被卡住”将与模式不匹配
最佳答案
你可以尝试这样测试
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
匹配任何字母数字字符,就像 [a-zA-Z0-9]
\\s
是空格类
+
表示 +
之前的元素必须至少找到一次。
关于java - 如何使用Java正则表达式来匹配这个模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802346/