Skip to content
Advertisement

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.

JavaScript

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)

Advertisement

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.

JavaScript
  • 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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement