I wanted to parse a String containing tags like the below into an array of tags using regex in Kotlin. But the regex returns only the first tag instead of an array of tags.
private val swiftTagRegex = """@([^:\s] )\w*""".toRegex()
"// @Flowers @apple @MANGO RedGrape".matches(swiftTagRegex)?.split("\\s".toRegex())?.toList()
return false
The same works fine on https://regexr.com/ Not sure what is missed out.
CodePudding user response:
Not sure what your actual code that produced a single result could have been, because your supplied code is uncompilable. matches
returns a Boolean
.
Anyway, what you need is findAll
. This returns a sequence, from which you can extract your group using map
to get your tags.
I'm pretty sure your \w*
does nothing because all word characters are captured in the previous part of the expression.
fun main() {
val swiftTagRegex = """@([^:\s] )\w*""".toRegex()
swiftTagRegex.findAll("// @Flowers @apple @MANGO RedGrape")
.map { it.groupValues[1] }
.toList()
.let(::println)
}
// prints
// [Flowers, apple, MANGO]