[英]How to check if a particular word from a string list contains in a string, but it should not be between any other words?
我需要检查字符串列表中的任何字符串是否在输入字符串中完全匹配(整个单词搜索),即它不应该匹配字符之间的单词。 例如检查下面的代码:
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
,这是不正确的。 它正在从hoping
词中获取pin
字符串。 只有当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");
}
}
}
请注意, \\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");
}
}
}
}
输出:
i was hoping the number => invalid
my pin is 123 => valid
the word, turnip ends with nip => valid
turnip is a vegetable => invalid
不使用Stream
API的解决方案:
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");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.