【问题标题】:Check whether sentence contains certain words检查句子是否包含某些单词
【发布时间】:2020-07-06 03:55:21
【问题描述】:

我有这样一句话:

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)。如果有任何匹配项,您就有匹配项。

标签: java arrays string if-statement contains


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!但我还有一个问题:变量 (s) 是一个字符串,对吧?因为我想要,我的代码从数组中返回包含的单词的位置。如果 s 是一个整数,那就很容易了
【解决方案2】:

我更喜欢在此处使用正则表达式方法,但有交替:

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

上述 sn-p 生成的确切正则表达式是:

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

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

【讨论】:

  • 请注意,这仅适用于数组元素不包含元字符。如果需要,您可以使用Pattern::quote 转义它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 2015-03-14
  • 2018-04-17
相关资源
最近更新 更多