Skip to content

Commit

Permalink
Fix regex named group extraction for jdk versions over jdk8
Browse files Browse the repository at this point in the history
  • Loading branch information
leomillon committed Sep 1, 2019
1 parent ee27993 commit 544ee87
Showing 1 changed file with 14 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ class ValidatorTemplateManager(private val value: String?) {
* @return the validator id, or null (if format is invalid)
*/
fun extractId(): String? = extractedTemplate
?.let { PARAMETERS_REGEX.matchEntire(it) }
?.groups
?.get("id")
?.value
.extractRegexGroup(PARAMETERS_REGEX, "id")

/**
* Extract the validator parameters.
Expand All @@ -64,10 +61,7 @@ class ValidatorTemplateManager(private val value: String?) {
* @return the ordered list of parameters, or empty (if format is invalid)
*/
fun extractParameters(): List<String> = extractedTemplate
?.let { PARAMETERS_REGEX.matchEntire(it) }
?.groups
?.get("parameters")
?.value
.extractRegexGroup(PARAMETERS_REGEX, "parameters")
?.split(PARAMETER_SEPARATOR_REGEX)
?.dropLastWhile { it.isEmpty() }
?.map { it.replace("\\\\;".toRegex(), ";") }
Expand All @@ -87,4 +81,16 @@ class ValidatorTemplateManager(private val value: String?) {

return if (index in parameters.indices) parameters[index] else null
}

/**
* Fallback method to handle regex group extraction as the stdlib-jdk8 does not support named group on MatchResult after JDK8.
*
* @see <a href="https://youtrack.jetbrains.com/issue/KT-20865">Retrieving groups by name is not supported on Java 9 even with `kotlin-stdlib-jre8` in the classpath</a>
*/
private fun String?.extractRegexGroup(regex: Regex, groupName: String): String? {
return this
?.let { regex.toPattern().matcher(it) }
?.takeIf { it.matches() }
?.group(groupName)
}
}

0 comments on commit 544ee87

Please sign in to comment.