如何在java中的String中查找整个单词

Nik*_*hev 25 java string pattern-matching stringtokenizer

我有一个字符串,我必须解析不同的关键字.例如,我有字符串:

"我会在123woods来见你"

我的关键字是

'123woods''森林'

我应该在每次有比赛时报告.还应考虑多次出现.然而,对于这个,我应该只在123woods匹配,而不是在树林.这消除了使用String.contains()方法.此外,我应该能够有一个列表/一组关键字,并同时检查它们的发生.在这个例子中,如果我有'123woods'和'come',我应该两次出现.方法执行在大文本上应该有点快.

我的想法是使用StringTokenizer,但我不确定它是否会表现良好.有什么建议?

Chr*_*ris 39

以下示例基于您的评论.它使用关键字列表,将使用字边界在给定的字符串中搜索.它使用Apache Commons Lang的StringUtils构建正则表达式并打印匹配的组.

String text = "I will come and meet you at the woods 123woods and all the woods";

List<String> tokens = new ArrayList<String>();
tokens.add("123woods");
tokens.add("woods");

String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找更高的性能,可以查看StringSearch:Java中的高性能模式匹配算法.

  • 使用 Java 8,不再需要 `StringUtils`。`String` 有静态的 `join()` 方法可以完成这项工作。 (2认同)

mor*_*rja 15

使用正则表达式+单词边界作为其他人回答.

"I will come and meet you at the 123woods".matches(".*\\b123woods\\b.*");
Run Code Online (Sandbox Code Playgroud)

将是真的.

"I will come and meet you at the 123woods".matches(".*\\bwoods\\b.*");
Run Code Online (Sandbox Code Playgroud)

将是假的.


Leo*_*tec 10

希望这对你有用:

String string = "I will come and meet you at the 123woods";
String keyword = "123woods";

Boolean found = Arrays.asList(string.split(" ")).contains(keyword);
if(found){
      System.out.println("Keyword matched the string");
}
Run Code Online (Sandbox Code Playgroud)

http://codigounico.blogspot.com/


a C*_*CVn 9

怎么样的Arrays.asList(String.split(" ")).contains("xx")

请参见String.split()以及如何测试数组是否包含特定值.


Hir*_*tel 5

有一种方法可以在Android中匹配 字符串中的精确单词:

String full = "Hello World. How are you ?";

String one = "Hell";
String two = "Hello";
String three = "are";
String four = "ar";


boolean is1 = isContainExactWord(full, one);
boolean is2 = isContainExactWord(full, two);
boolean is3 = isContainExactWord(full, three);
boolean is4 = isContainExactWord(full, four);

Log.i("Contains Result", is1+"-"+is2+"-"+is3+"-"+is4);

Result: false-true-true-false
Run Code Online (Sandbox Code Playgroud)

匹配单词的函数:

private boolean isContainExactWord(String fullString, String partWord){
    String pattern = "\\b"+partWord+"\\b";
    Pattern p=Pattern.compile(pattern);
    Matcher m=p.matcher(fullString);
    return m.find();
}
Run Code Online (Sandbox Code Playgroud)

完毕