Search code examples
regexkotlinregular-language

Kotlin Regex Boundary Matching Not working


I'm trying to parse a word, bounded by whitespace or punctuation on either side.

I tried this:


fun main(args: Array<String>) {
    val regex = "\bval\b".toRegex();
    regex.matches("fn foo() { val x = 2;} x;").also { println(it) }
}

But this prints out false. I tested the regex on here https://regex101.com/r/vNBefF/2 and it works, matching against the input string.

What am I doing wrong?


Solution

  • I think you're using the wrong method. From the KotlinDoc:

    Indicates whether the regular expression matches the entire input.

    I think what you may want is containsMatchIn. You can play with this on the playground.