[英]Match any word of a List/Array in a Sentence java
我有一個如下所示的單詞List
List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");
如何理解String
包含List
任何一個單詞。 喜歡....
String name1 = "Adam Smith"; // false (not found)
String name2 = "Late H Milton"; // true (found Late)
String name3 = "S/O Furi Kerman"; // true (found S/O)
String name4 = "Conl Faruk"; // false (not found)
String name5 = "Furi Kerman WO"; // true (found WO)
正則表達高度贊賞。
boolean containsForbiddenName = forbiddenWordList.stream()
.anyMatch(forbiddenName -> name.toLowerCase()
.contains(forbiddenName.toLowerCase()));
將列表轉換為帶有|的字符串 分隔符
String listDelimited = String.join(“|”,forbiddenWordList)
創建正則表達式
模式forbiddenWordPattern = Pattern.compile(listDelimited,Pattern.CASE_INSENSITIVE);
測試你的文字
boolean hasForbiddenWord = forbiddenWordPattern.matcher(text).find();
(類似於@Maurice Perry的回答)
你可以像這樣使用:
對單詞 ( stream
)進行迭代,如果任何單詞(名為w
)與條件( contains
)匹配,則返回true
public static boolean isForbidden(String word, List<String> words) {
return words.stream().anyMatch(w -> (word.toLowerCase().contains(w.toLowerCase())));
}
使用正則表達式 ,它將從List
構建模式本身
public static boolean isForbidden1(String word, List<String> words) {
String forbiddenWordPattern = String.join("|", words);
return Pattern.compile(forbiddenWordPattern, Pattern.CASE_INSENSITIVE)
.matcher(word)
.find();
}
該列表可以表示為一種模式:
Pattern forbiddenWordPattern
= Pattern.compile("LATE|S/O|SO|W/O|WO", Pattern.CASE_INSENSITIVE);
要測試文本中是否存在單詞,您可以:
boolean hasForbiddenWord = forbiddenWordPattern.matcher(text).find();
最后,我自己幫助了所有人......
String regex = String.join("|", forbiddenWordList.stream().map(word -> "\\b" + word + "\\b").collect(Collectors.toList()));
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
System.out.println(pattern.matcher(name).find());
單詞邊界( \\\\b
)有助於找到確切的單詞,而不是匹配的文本。 謝謝大家的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.