如何检查字符串列表中的特定单词是否包含在字符串中,但不应在其他任何单词之间?

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

我需要检查字符串列表中的任何字符串是否在输入字符串中完全匹配(整个单词搜索),即它不应匹配字符之间的单词。 例如检查下面的代码:
String input = "i was hoping the number";
String[] valid = new String[] { "nip", "pin" };
if (Arrays.stream(valid).anyMatch(input::contains)) {
    System.out.println("valid");
}

我的输出是

valid
,这是不正确的。它正在从
pin
单词中获取
hoping
字符串。我只有在单词分开的情况下才能匹配。
	

如下:
java arrays regex string stream
2个回答
0
投票
pin

注意,我在匹配的单词之前和之后添加了
import java.util.Arrays;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String input = "i was hoping the number";
        String[] valid = new String[] { "nip", "pin" };
        if (Arrays.stream(valid).anyMatch(p -> Pattern.compile("\\b" + p + "\\b").matcher(input).find())) {
            System.out.println("valid");
        }
    }
}
wordboundare

,以为它们创建单词边界。

一些测试:

\b

输出:

import java.util.Arrays;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String[] testStrings = { "i was hoping the number", "my pin is 123", "the word, turnip ends with nip",
                "turnip is a vegetable" };
        String[] valid = new String[] { "nip", "pin" };
        for (String input : testStrings) {
            if (Arrays.stream(valid).anyMatch(p -> Pattern.compile("\\b" + p + "\\b").matcher(input).find())) {
                System.out.println(input + " => " + "valid");
            } else {
                System.out.println(input + " => " + "invalid");
            }
        }
    }
}

sodution不使用

i was hoping the number => invalid
my pin is 123 => valid
the word, turnip ends with nip => valid
turnip is a vegetable => invalid

api:

Stream

import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "i was hoping the number"; String[] valid = new String[] { "nip", "pin" }; for (String toBeMatched : valid) { if (Pattern.compile("\\b" + toBeMatched + "\\b").matcher(input).find()) { System.out.println("valid"); } } } }
this将输入分为单词(由一个或多个字符划分),并检查是否有任何单词在有效的单词中。
    

0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.