[英]How to check if a particular word from a string list contains in a string, but it should not be between any other words?
I need to check if any string from a string list matches wholly (whole word search) within the input string ie it should not match the word in between characters.我需要检查字符串列表中的任何字符串是否在输入字符串中完全匹配(整个单词搜索),即它不应该匹配字符之间的单词。 eg check the code below:例如检查下面的代码:
String input = "i was hoping the number";
String[] valid = new String[] { "nip", "pin" };
if (Arrays.stream(valid).anyMatch(input::contains)) {
System.out.println("valid");
}
My output is valid
, which is not correct.我的输出是valid
,这是不正确的。 It is fetching the pin
string from the hoping
word.它正在从hoping
词中获取pin
字符串。 I should be able to match only if the pin
word is separate.只有当pin
词是分开的时,我才应该能够匹配。
Do it as follows:请按以下步骤操作:
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");
}
}
}
Note that \\b
is used for word boundary which I have added before and after the matching words to create word boundary for them.请注意, \\b
用于词边界,我在匹配词之前和之后添加了它来为它们创建词边界。
Some more tests:还有一些测试:
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");
}
}
}
}
Output:输出:
i was hoping the number => invalid
my pin is 123 => valid
the word, turnip ends with nip => valid
turnip is a vegetable => invalid
Solution without using Stream
API:不使用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.