简体   繁体   English

如何使用Java中的Pattern Matcher类从给定的String中找到两个或多个匹配的单词?

[英]How to Find two or more words matching from given String using Pattern Matcher class in java?

I used below code for the matching of two words from the given string, but it's not working. 我使用下面的代码来匹配给定字符串中的两个单词,但它不起作用。

String inputText = "I want to know relating to cloud based erp services.";
Set<String> words = new HashSet<String>();
words.add("erp");
words.add("cloud");

Pattern p = Pattern.compile("erp|cloud");

Matcher m = p.matcher(inputText);
if (m.find())
{
    return m.group();
    System.out.println("Yes we providing it.");
}

Modify your code as : 将您的代码修改为:

  Pattern p = Pattern.compile("erp|cloud");

    Matcher m = p.matcher(inputText);
    String match = "";
    if (m.find())
    {
        match =  m.group();
        System.out.println("Yes we providing it.");
    }
    return match;

You may just check if your input contains all the strings from the hash set using a simple check: use .filter(s -> inputText.contains(s)) and then check if the filtered set size is equal to the hashset size. 您可以使用简单的检查检查输入是否包含散列集中的所有字符串:use .filter(s -> inputText.contains(s)) ,然后检查过滤的集合大小是否等于散列集大小。 If yes, all the terms are present in the string: 如果是,则字符串中包含所有条款:

String inputText = "I want to know relating to cloud based erp services.";
Set<String> words = new HashSet<String>();
words.add("erp");
words.add("cloud");

if (words.stream().filter(s -> inputText.contains(s)).count() == words.size()) {
    System.out.println("Yes we providing it.");
} else {
    System.out.println("No, we are not providing it.");
}

See the Java demo . 请参阅Java演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM