How to match the first word after an expression in a string using RegEx with Kotlin

1 Answer

0 votes
fun findNextWord(text: String, expression: String) {
    val escapedExpr = Regex.escape(expression)
    val pattern = Regex("$escapedExpr\\s+(\\w+)")
    val match = pattern.find(text)

    if (match != null) {
        println("The first word after '$expression' is: ${match.groupValues[1]}")
    } else {
        println("No match found!")
    }
}

fun main() {
    val text = "The quick brown fox jumps over the lazy dog."
    val expression = "fox"

    findNextWord(text, expression)
}

 
  
/*
run:
  
The first word after 'fox' is: jumps

*/

 



answered Jun 16, 2025 by avibootz
...