Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match any word of a List/Array in a Sentence java

I have an List of word like below

List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");

How can I understand a String Contains any one of the word of the List. like....

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)

Regular Expression highly appreciated.

like image 533
Mr. Mak Avatar asked Dec 03 '22 21:12

Mr. Mak


2 Answers

  1. turn the list to a string with the | delimiter

    String listDelimited = String.join("|", forbiddenWordList )

  2. create the regex

    Pattern forbiddenWordPattern = Pattern.compile(listDelimited , Pattern.CASE_INSENSITIVE);

  3. test your text

    boolean hasForbiddenWord = forbiddenWordPattern.matcher(text).find();

(similar to the answer of @Maurice Perry)

like image 40
Ofer Skulsky Avatar answered Dec 11 '22 15:12

Ofer Skulsky


boolean containsForbiddenName = forbiddenWordList.stream()
     .anyMatch(forbiddenName -> name.toLowerCase()
          .contains(forbiddenName.toLowerCase()));
like image 50
Adam Siemion Avatar answered Dec 11 '22 17:12

Adam Siemion