Provide access to named groups of regex match result on JDK8.

#KT-12753 Fixed
This commit is contained in:
Ilya Gorbunov
2016-06-15 23:55:33 +03:00
parent 25974be3f8
commit a45da393b9
6 changed files with 94 additions and 2 deletions
@@ -2,6 +2,7 @@
package kotlin.internal
import java.io.Closeable
import java.util.regex.MatchResult
internal open class PlatformImplementations {
@@ -16,6 +17,10 @@ internal open class PlatformImplementations {
}
}
public open fun getMatchResultNamedGroup(matchResult: MatchResult, name: String): MatchGroup? {
throw UnsupportedOperationException("Retrieving groups by name is not supported on this platform.")
}
companion object {
@JvmField
@InlineExposed
@@ -52,5 +57,7 @@ internal open class PlatformImplementations {
}
}
}
@@ -36,8 +36,17 @@ public interface MatchGroupCollection : Collection<MatchGroup?> {
* corresponds to the entire match.
*/
public operator fun get(index: Int): MatchGroup?
}
// TODO: Provide get(name: String) on JVM 7+
/**
* Extends [MatchGroupCollection] by introducing a way to get matched groups by name, when regex supports it.
*/
public interface MatchNamedGroupCollection : MatchGroupCollection {
/**
* Returns a named group with the specified [name].
* @return An instance of [MatchGroup] if the group with the specified [name] was matched or `null` otherwise.
*/
public operator fun get(name: String): MatchGroup?
}
/**
@@ -19,6 +19,7 @@ package kotlin.text
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.internal.DefaultPlatformImplementations
private interface FlagEnum {
public val value: Int
@@ -231,7 +232,7 @@ private class MatcherMatchResult(private val matcher: Matcher, private val input
override val value: String
get() = matchResult.group()
override val groups: MatchGroupCollection = object : MatchGroupCollection {
override val groups: MatchGroupCollection = object : MatchNamedGroupCollection {
override val size: Int get() = matchResult.groupCount() + 1
override fun isEmpty(): Boolean = false
override fun contains(element: MatchGroup?): Boolean = this.any { it == element }
@@ -245,6 +246,9 @@ private class MatcherMatchResult(private val matcher: Matcher, private val input
else
null
}
override fun get(name: String): MatchGroup? {
return DefaultPlatformImplementations.INSTANCE.getMatchResultNamedGroup(matchResult, name)
}
}
private var groupValues_: List<String>? = null