【问题标题】:regular expression to find repeated words in a sentence正则表达式查找句子中重复的单词
【发布时间】:2019-01-24 11:17:43
【问题描述】:

我正在尝试编写一个正则表达式来查找句子中的重复单词。 好吧,我尝试使用这个表达式:

\b(\w+)\b.*?\1

从句子"Hello how in the Hello world are you ? are you okay? Hello" 中选择 3x 'hello'、2x 'are' 和 2x 'you',我知道这显然是错误的,因为它考虑了整个单词组而不是一个特定的单词! 那么您能纠正我的表达方式或提出您自己的解决方案吗?
我正在使用Matcher 类尝试使用matcher.find() 的while 循环中的计数变量找出给定单词的出现次数。

【问题讨论】:

  • 简单地分割每个空格然后将所有项目放在Multiset / CountedSet / CountingSet 中会更容易。

标签: java regex


【解决方案1】:

试试这个模式:(?<=\b| )([^ ]+)(?= |$).+(\1) 它检测第一个单词,该单词在字符串中出现多次。

Demo

【讨论】:

    【解决方案2】:

    Regex 并不适合这样的工作。正则表达式不倾向于 count 事物。您可以在正则表达式的帮助下做到这一点,但如果不是不可能的话,仅使用正则表达式是非常困难的。

    这是我的尝试:

    String sentence = "Hello how in the Hello world are you ? are you okay? Hello";
    String[] words = Pattern.compile("\\W+").split(sentence); // split the sentence into words
    
    Map<String, Integer> list = Arrays.stream(words)
            .collect(Collectors.groupingBy(x -> x))
            .entrySet().stream()
            .filter(x -> x.getValue().size() != 1) // remove the words that are not repeated 
            .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().size()));
    

    【讨论】:

    • 谢谢,这真的很有帮助
    猜你喜欢
    • 2013-11-08
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多