栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Java Regex,如何检查字符串是否包含集合中的任何单词?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Java Regex,如何检查字符串是否包含集合中的任何单词?

TL; DR 对于简单的子字符串

contains()
最好,但对于仅匹配整个单词的正则表达式可能更好。

查看哪种方法更有效的最佳方法是对其进行测试。

您可以使用

String.contains()
代替
String.indexOf()
来简化您的非正则表达式代码。

要搜索其他单词,正则表达式如下所示:

apple|orange|pear|banana|kiwi

|
作品作为
OR
正则表达式中的作品。

我非常简单的测试代码如下所示:

public class TestContains {   private static String containsWord(Set<String> words,String sentence) {     for (String word : words) {       if (sentence.contains(word)) {         return word;       }     }     return null;   }   private static String matchesPattern(Pattern p,String sentence) {     Matcher m = p.matcher(sentence);     if (m.find()) {       return m.group();     }     return null;   }   public static void main(String[] args) {     Set<String> words = new HashSet<String>();     words.add("apple");     words.add("orange");     words.add("pear");     words.add("banana");     words.add("kiwi");     Pattern p = Pattern.compile("apple|orange|pear|banana|kiwi");     String noMatch = "The quick brown fox jumps over the lazy dog.";     String startMatch = "An apple is nice";     String endMatch = "This is a longer sentence with the match for our fruit at the end: kiwi";     long start = System.currentTimeMillis();     int iterations = 10000000;     for (int i = 0; i < iterations; i++) {       containsWord(words, noMatch);       containsWord(words, startMatch);       containsWord(words, endMatch);     }     System.out.println("Contains took " + (System.currentTimeMillis() - start) + "ms");     start = System.currentTimeMillis();     for (int i = 0; i < iterations; i++) {       matchesPattern(p,noMatch);       matchesPattern(p,startMatch);       matchesPattern(p,endMatch);     }     System.out.println("Regular expression took " + (System.currentTimeMillis() - start) + "ms");   }}

我得到的结果如下:

Contains took 5962msRegular expression took 63475ms

显然,时间的长短取决于要搜索的单词数和要搜索的字符串,但是

contains()
对于像这样的简单搜索,它似乎比正则表达式快约10倍。

通过使用正则表达式在另一个字符串中搜索字符串,您正在使用大锤破解螺母,因此我想我们应该不会感到惊讶,因为它速度较慢。保存正则表达式,以在您要查找的模式更复杂时使用。

您可能要使用正则表达式的一种情况是if

indexOf()
并且
contains()
不会执行该工作,因为 您只想匹配整个单词
,而不仅仅是子字符串,例如,您想要匹配
pear
但不匹配
spears
。正则表达式具有单词边界的概念,因此可以很好地处理这种情况。

在这种情况下,我们将模式更改为:

b(apple|orange|pear|banana|kiwi)b

b
只匹配单词开头或结尾的“ 说”,方括号将OR表达式归为一组。

请注意,在代码中定义此模式时,您需要使用另一个反斜杠来转义反斜杠:

 Pattern p = Pattern.compile("\b(apple|orange|pear|banana|kiwi)\b");


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610384.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号