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

2 回答 2

2

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

if (Arrays.stream(stringArray).anyMatch(s -> line.contains(s)) {
    // Do something...
于 2020-03-25T15:11:58.917 回答
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.

于 2020-03-25T15:16:37.573 回答