How to find the whole word in kotlin using regex

余生长醉 提交于 2021-02-04 19:24:07

问题


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 - your word 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!