[英]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.