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

时间:2020-03-25 15:09:26

标签: java arrays string if-statement contains

我有一句话:

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!");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

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一起使用。