'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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karsten Gabriel |
