Kotlin introduces additional types like Regex for working with regular expressions. It uses kotlin.text.MatchResult that may be confused with java.util.regex.MatchResult.
Code example
// parse text with java library
val src = "123 23 45 67"
val patterns = arrayOf(
Pattern.compile("\\d+"),
Pattern.compile("\\s+"))
val matcher: Matcher = patterns[0].matcher(src).apply{
region(0, src.length)
}
var foundMatch = false
with(matcher) {
while (regionStart() < regionEnd()) {
foundMatch = false
patterns.forEachIndexed { index, pattern ->
usePattern(pattern)
if (lookingAt()) {
// do something
println("found match for ${patterns[index]} : ${src.substring(start(), end())}")
foundMatch = true
region(end(), regionEnd())
return@forEachIndexed
}
}
if (!foundMatch) throw IllegalStateException("Unknown token at ${regionStart()}")
}
}
if (!foundMatch)
throw IllegalStateException("Unknown token at ${matcher.regionStart()}")
}