我有一个完整的句子,如下所示。
“Stackoverflow 是最好的,stackoverflow.com 非常棒!!!”
我需要找到与给定子字符串匹配的第一个完整单词。例如,如果输入是“overflow”,则结果应该是“Stackoverflow”,因为它是包含给定单词的第一个单词。
我尝试了以下代码片段,但对我不起作用。
String fullText="Stackoverflow is the best and stackoverflow.com rocks !!!";
String token = "overflow";
Pattern pattern = Pattern.compile(token);
Matcher matcher = pattern.matcher(fullText);
while (matcher.find())
{
System.out.println("Whole word is "+matcher.group());
}
我得到“溢出”作为输出。我的代码可能有什么问题?
最佳答案
What could be wrong with my code?
因为你的正则表达式只匹配overflow
而不是包含它的单词
改用以下正则表达式:
\\b\\S*overflow\\S*
String token = "\\b\\S*overflow\\S*";
Pattern pattern = Pattern.compile(token);
Matcher matcher = pattern.matcher(fullText);
if (matcher.find())
{
System.out.println("Whole word is :"+matcher.group());
}
说明:
\b
匹配单词边界\\S*
匹配零个或多个无空格字符overflow
匹配字面上的溢出\\S*
匹配零个或多个非空格字符
替代方案二:使用 split 并迭代每个单词并在找到单词时中断
String fullText="Stackoverflow is the best and stackoverflow.com rocks !!!";
String [] strWords = fullText.split("\\s");
for(String strWord:strWords){
if(strWord.contains("overflow")){
System.out.println(strWord);
break;
}
}
关于java - 在 Java 的长文本中查找给定子字符串的第一个匹配的整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613625/