检查句子是否包含某些单词

Check whether sentence contains certain words

我有这样一句话:

I`ve got a Pc

还有一组话:

Hello
world
Pc
dog

如何检查句子中是否包含这些词?在此示例中,我将与 Pc.

进行匹配

这是我目前得到的:

public class SentenceWordExample {
    public static void main(String[] args) {
        String sentence = "I`ve got a Pc";
        String[] words = { "Hello", "world", "Pc", "dog" };

       // I know this does not work, but how to continue from here?
       if (line.contains(words) {
            System.out.println("Match!");
       } else {
            System.out.println("No match!");
        }
    }
}

我会流式传输数组,然后检查字符串是否包含它的任何元素:

if (Arrays.stream(stringArray).anyMatch(s -> line.contains(s)) {
    // Do something...

我更喜欢在这里使用正则表达式方法,并进行交替:

String line = "I`ve got a Pc";
String[] array = new String[2];
array[0] = "Example sentence";
array[1] = "Pc";
List<String> terms = Arrays.asList(array).stream()
    .map(x -> Pattern.quote(x)).collect(Collectors.toList());
String regex = ".*\b(?:" + String.join("|", terms) + ")\b.*";
if (line.matches(regex)) {
    System.out.println("MATCH");
}

上面代码片段生成的确切正则表达式是:

.*\b(?:Example sentence|Pc)\b.*

也就是说,我们形成一个交替,其中包含我们要在输入字符串中搜索的所有关键字术语。然后,我们将该正则表达式与 String#matches.

一起使用