user16269092
user16269092

Reputation:

How to find specific keyword in a string?

I have following code:

val contains = jobAd.toString().lowercase()
                .contains(keyword.lowercase())

Problem is its getting hit even the string have "javascript". But i only want it to behit when it's actually the word java.

What am i doing wrong?

Upvotes: 0

Views: 801

Answers (1)

Karsten Gabriel
Karsten Gabriel

Reputation: 3652

If you want to match only an entire word, you can use word boundaries in a regular expression like this:

fun String.findWord(word: String) = "\\b$word\\b".toRegex().containsMatchIn(this)

Then you can write for instance:

"I like Java!".findWord("Java") // true
"I like JavaScript".findWord("Java") // false

Note that this is case sensitive and not very robust, because for instance, it is possible to inject a regular expression. This is just to give you the general idea.

Upvotes: 1

Related Questions