问题
I want to find the whole word in string. But I don't know how to find the all word in kotlin. My finding word is [non alpha]cba[non alpha]. My example code is bellows.
val testLink3 = """cba@cba cba"""
val word = "cba"
val matcher = "\\b[^a-zA-Z]*(?i)$word[^a-zA-Z]*\\b".toRegex()
val ret = matcher.find(testLink3)?.groupValues
But output of my source code is "cba" My expected value is string array such as "{cba, cba, cba}". How to find this value in kotlin language.
回答1:
You may use
val testLink3 = """cBa@Cba cbA123"""
val word = "cba"
val matcher = "(?i)(?<!\\p{L})$word(?!\\p{L})".toRegex()
println(matcher.findAll(testLink3).map{it.value}.toList() )
println(matcher.findAll(testLink3).count() )
// => [cBa, Cba, cbA]
// => 3
See the online Kotlin demo.
To obtain the list of matches, you need to run the findAll
method on the regex object, map the results to values and cast to list:
.findAll(testLink3).map{it.value}.toList()
To count the matches, you may use
matcher.findAll(testLink3).count()
Regex demo
(?i)
- case insensitive modifier(?<!\\p{L})
- a negative lookbehind that fails the match if, immediately to the left of the current location, there is a letter$word
- yourword
variable value(?!\\p{L})
- a negative lookahead that fails the match if, immediately to the right of the current location, there is a letter.
来源:https://stackoverflow.com/questions/52628091/how-to-find-the-whole-word-in-kotlin-using-regex