Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Regex named groups support

Does Kotlin have support for named regex groups?

Named regex group looks like this: (?<name>...)

like image 747
gs_vlad Avatar asked May 07 '16 12:05

gs_vlad


3 Answers

According to this discussion,

This will be supported in Kotlin 1.1. https://youtrack.jetbrains.com/issue/KT-12753

Kotlin 1.1 EAP is already available to try.


"""(\w+?)(?<num>\d+)""".toRegex().matchEntire("area51")!!.groups["num"]!!.value

You'll have to use kotlin-stdlib-jre8.

like image 141
Vadzim Avatar answered Nov 17 '22 05:11

Vadzim


As of Kotlin 1.0 the Regex class doesn't provide a way to access matched named groups in MatchGroupCollection because the Standard Library can only employ regex api available in JDK6, that doesn't have support for named groups either.

If you target JDK8 you can use java.util.regex.Pattern and java.util.regex.Matcher classes. The latter provides group method to get the result of named-capturing group match.

like image 7
Ilya Avatar answered Nov 17 '22 05:11

Ilya


As of Kotlin 1.4, you need to cast result of groups to MatchNamedGroupCollection:

val groups = """(\w+?)(?<num>\d+)""".toRegex().matchEntire("area51")!!.groups as? MatchNamedGroupCollection 
if (groups != null) {
    println(groups.get("num")?.value)
}

And as @Vadzim correctly noticed, you must use kotlin-stdlib-jdk8 instead of kotlin-stdlib:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}

Here is a good explanation about it

like image 2
Dmitrii Bocharov Avatar answered Nov 17 '22 03:11

Dmitrii Bocharov