gpt4 book ai didi

java - 在java中使用正则表达式来查找短语

转载 作者:行者123 更新时间:2023-11-29 06:03:19 25 4
gpt4 key购买 nike

您好,我正在尝试使用正则表达式来发现字符串中的短语我有以下代码:它似乎没有找到所有的两个单词短语。

public static void main(String[] args) {
String inputText = "test and test Test hello hello hello test test hello hello ";

//Pattern pattern = Pattern.compile("((\\w{3,}?)\\W(\\w{3,}?)\\W).*\\2\\W\\3", Pattern.CASE_INSENSITIVE);

Pattern twoWordPrasePattern = Pattern.compile("(([a-zA-Z]{3,})\\W([a-zA-Z]{3,})\\W).*\\2\\W\\3", Pattern.CASE_INSENSITIVE);

Matcher matcher = twoWordPrasePattern.matcher(inputText);
while (matcher.find()) {

System.out.println(inputText.substring(matcher.start(), matcher.end()));

System.out.println(matcher.group(1));

}

}

我正在努力解决这个问题,为什么 hello hello 组不退出?任何帮助表示感谢。我怎样才能改变模式来找到所有的短语?理查德

最佳答案

matcher.find() 总是从上一个匹配停止的地方搜索。第一次调用发现这个:

test Test hello hello hello test test

所以剩下要搜索的就是

hello hello 

最后。最后的 hello hello 与您的模式不匹配(因为它只有两个词,而您的模式至少需要四个词:它将两个词作为组 23,然后找到 \2\W\3),所以它没有得到输出。

关于java - 在java中使用正则表达式来查找短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com