Regex Outputing the Wrong Index

Viewed 25

I'm trying to find the index of the first word detected by this pattern.

val text = " _his_ fancy;"
val startIndex = 0
val pattern: Regex = "[a-zA-z0-9]".toRegex()
var match = pattern.find(text, startIndex)
println(idx)

However, when I ran this I got index of 1 instead of 2. Can someone please tell me what I did wrong?

1 Answers

You have a lowercase z in the A-z section, which represents a big range that goes from uppercase A to lowercase z, and that includes all upper- and lowercase letters, plus a few others in between. The underscore character happens to be in that range too.

I guess you just wanted A-Z here instead.

Related