gpt4 book ai didi

java - 无法匹配单词的部分内容

转载 作者:行者123 更新时间:2023-12-01 12:09:08 25 4
gpt4 key购买 nike

我编写了一个程序来复制第一行,其中包含匹配的单词、单词或单词的一部分。我使用以下代码得到了一个或多个单词的结果。当我输入单词的一部分时,我得到的是空值。

public static void main(String[] args) {

String paragraph="First time in a long time the cricket team is in Kandy and there is no rain and the skies are blue. Strange days. Hope it stays that way";
String searchWord="lo";
Pattern p = Pattern.compile("([A-Z][^.?!]*?)?(?<!\\w)(?i)(" + searchWord + ")(?!\\w)[^.?!]*?[.?!]{1,2}\"?");
Matcher m = p.matcher(paragraph);
String sentence = null;
while (m.find()) {
sentence = m.group();
break;
}
System.out.println(sentence);
}

请建议我如何搜索部分单词?

最佳答案

是的,您必须得到一个空匹配作为输出,因为子字符串 lo 后跟字符串 long 中的单词字符 n。因此,将正则表达式中的负向先行 (?!\\w) 更改为正向先行 (?=\\w) 以获得匹配。

Pattern p = Pattern.compile("([A-Z][^.?!]*?)?(?<!\\w)(?i)(" + searchWord + ")(?=\\w)[^.?!]*?[.?!]{1,2}\"?");

DEMO

String paragraph="First time in a long time the cricket team is in Kandy and there is no rain and the skies are blue. Strange days. Hope it stays that way";
String searchWord="lo";
Pattern p = Pattern.compile("([A-Z][^.?!]*?)?(?<!\\w)(?i)(" + searchWord + ")(?=\\w)[^.?!]*?[.?!]{1,2}\"?");
Matcher m = p.matcher(paragraph);
String sentence = null;
while (m.find()) {
sentence = m.group();
break;
}
System.out.println(sentence);

输出:

First time in a long time the cricket team is in Kandy and there is no rain and the skies are blue.

关于java - 无法匹配单词的部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27372842/

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