正则表达式匹配两个以上的Java元素

正则表达式匹配两个以上的Java元素,java,regex,Java,Regex,我正在尝试匹配字符串中的两个或多个单词。字符串是My/word-example/wordI-want-extractMy-example。到目前为止,我所做的是: String test = "My/word example/word"; Pattern pattern = Pattern.compile("((.*)\\/word){2,}"); Matcher match = pattern.matcher(test); if

我正在尝试匹配字符串中的两个或多个单词。字符串是
My/word-example/word
I-want-extract
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));
            }

但是它只打印
示例/word
,有什么想法吗?

您可以使用非贪婪*运算符:

((.*?)\/word)

您可以使用非贪婪*-运算符:

((.*?)\/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

如果您与捕获组有任何重复,它将只捕获该组的最终匹配。您最好的选择是简化正则表达式,使其仅匹配一个单词,然后重复使用
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

是否可能使用了错误的组号?我认为如果您使用
组(2)

可能是您使用了错误的组号,它将返回您正在查找的结果?我认为如果您使用
组(2)

可以将被动组用于
/word
部分,并对匹配的结果进行迭代以构造最终字符串,那么它将返回您要查找的结果

String test = "My/word example/word";
Pattern pattern = Pattern.compile("(\\w*)(?:\\/word)");
Matcher match = pattern.matcher(test);
String result = "";
while (match.find()) {
    result += match.group(1) + " ";
}

System.out.println(result.trim());
输出将是:

My example

您可以对
/word
部分使用被动组,并对匹配的结果进行迭代以构造最终字符串

String test = "My/word example/word";
Pattern pattern = Pattern.compile("(\\w*)(?:\\/word)");
Matcher match = pattern.matcher(test);
String result = "";
while (match.find()) {
    result += match.group(1) + " ";
}

System.out.println(result.trim());
输出将是:

My example

您不能将
My
放在一个捕获组中,将
example
放在另一个捕获组中吗?这种模式应该有多普遍?你不能在一个捕获组中设置
My
,在另一个捕获组中设置
example
?这个模式应该有多普遍?加上这个答案,按组获取(2)加上这个答案,按组获取(2)