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

问题描述 投票:1回答:2

我的句子像:

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!");
        }
    }
}
java arrays string if-statement contains
2个回答
1
投票

我将流传输数组,然后检查字符串是否包含其任何元素:

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

0
投票

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

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);
String regex = ".*\\b(?:" + String.join("|", terms) + ")\\b.*";
if (line.matches(Pattern.quote(regex))) {
    System.out.println("MATCH");
}

以上代码段生成的确切正则表达式为:

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

即,我们形成一个替换,其中包含要在输入字符串中搜索的所有关键字词。然后,我们将该正则表达式与String#matches一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.