nz_21
nz_21

Reputation: 7383

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?

Upvotes: 2

Views: 1423

Answers (1)

jasondlee
jasondlee

Reputation: 286

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.

Upvotes: 7

Related Questions