检查句子是否包含特定单词

3

我有一句话,类似于:

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

你只需要遍历数组中的所有元素,然后使用 line.contains(arrayElement)。如果有任何匹配项,那么就是有匹配项了。 - Zabuzard
2个回答

2

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

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

非常感谢!但我还有一个问题:变量(s)是一个String,是吗?因为我想让我的代码返回数组中包含单词的位置。如果s是整数,那就容易了。 - Marco

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

1
请注意,这仅适用于数组元素不包含元字符的情况。如果需要,您可以使用Pattern :: quote转义它们。 - Andy Turner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接