Skip to content

Find exact match from Array

In java I want to iterate an array to find any matching words from my input string

if the input string is appended to numbers it should return true.

Array arr = {"card","creditcard","debitcard"}
String inputStr = "need to discard pin" --> Return False
String inputStr = "need to 444card pin" --> Return True if its followed by number

I tried the below code, but it returns true as it takes “card” from the “discard” string and compares, but I need to do an exact match

Arrays.stream(arr).anymatch(inputString::contains)

Answer

The problem with most answers here is that they do not take punctuation into consideration. To solve this, you could use a regular expression like below.

String[] arr = { "card", "creditcard", "debitcard" };
String inputStr = "You need to discard Pin Card.";

Arrays.stream(arr)
    .anyMatch(word -> Pattern
        .compile("(?<![a-z-])" + Pattern.quote(word) + "(?![a-z-])", Pattern.CASE_INSENSITIVE)
        .matcher(inputStr)
        .find());
  • With Pattern.quote(word), we escape any character within each word with is a special character in the context of a regular expression. For instance, the literal string a^b would never match, because ^ means the start of a string if used in a regular expression.

  • (?<![a-z-]) and (?![a-z-]) mean that there is not a word character immediately preceding or succeeding the word. For instance, discard will not match, even if it contains the word card. I have used only lowercase in these character classes because of the next bullet:

  • The flag CASE_INSENSITIVE passed to the compile method causes the pattern to be matched in a case-insensitive manner.

Online demo