我正在尝试匹配字符串中的两个或多个单词。该字符串是 My/word example/word
我想提取 My example
。到目前为止我所做的是:
String test = "My/word example/word";
Pattern pattern = Pattern.compile("((.*)\\/word){2,}");
Matcher match = pattern.matcher(test);
if (match.find()) {
System.out.println(match.group(1));
}
但它只打印example/word
,有什么想法吗?
最佳答案
如果您对捕获组有任何重复,它只会捕获该组的最终匹配。这里最好的选择是将正则表达式简化为仅匹配一个单词,然后重复使用 match.find()
直到找不到匹配项:
String test = "My/word example/word";
Pattern pattern = Pattern.compile("(\\w+)/word");
Matcher match = pattern.matcher(test);
while (match.find()) {
System.out.println(match.group(1));
}
在这里添加一些逻辑应该不难,以便仅在找到两个或更多匹配项时才打印。
另请注意,我稍微修改了您的正则表达式,不需要转义正斜杠,并且我将 .*
替换为 \w+
,这应该更好,因为您不会贪婪地匹配到最后一个 /word
。
关于java - 正则表达式匹配两个以上元素Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9725155/