androidregexkotlin

Kotlin exact String match for a given word, rather than embedded words?


I'm trying to look through strings for given keywords, but in some cases, the keywords are contained within other words, resulting in a false-positive. I'm sure the answer to this is regex, I'm just not sure the correct way to implement it. Here's an example of what's happening.

val keyword = "NFL"

val someCompareString = "This week in the NFL something is happening."
val someOtherCompareString = "In the middle east there is an ongoing conflict of some kind."

// I expect this to return TRUE
if (someCompareString.lowercase().contains(keyword))

// I expect this to return FALSE
if (someOtherCompareString.lowercase().contains(keyword))

The second string is returning "true", because the word "conflict" does contain "nfl". I understand what's happening, but without doing something goofy to the string like taking keyword and adding a space/comma/exclamation/period both before and after and then checking all of those possible combinations... I'm not sure what the correct way to handle this is. Anyone have any advice?


Solution

  • The key is to look for whole words, which can be done by using word boundaries (\b) in your regex.

    // Create a regex pattern with word boundaries
    val pattern = val pattern = "\\b$keyword\\b".toRegex(RegexOption.IGNORE_CASE)
    
    // Check for matches
    println(pattern.containsMatchIn(someCompareString)) // Expected: true
    println(pattern.containsMatchIn(someOtherCompareString)) // Expected: false