Ayfri
11/19/2021, 4:33 PMselection
) that is equal to this pattern : [key=value, key=value, key=value]
and I want to split it to a map containing all the keys and values, is there a simple way than this ?
val attributes = selection.replace("[(\\w+)]".toRegex(), "$1").replace("\\s+".toRegex(), "").split(',').associate { it.substringBefore('=') to it.substringAfter('=') }
Joffrey
11/19/2021, 4:37 PM// compile those only once
val entrySeparator = Regex("""\s*,\s*""")
val keyValueSeparator = Regex("""\s*=\s*""")
selection.removePrefix("[")
.removeSuffix("]")
.split(entrySeparator)
.associate {
val (key, value) = it.split(keyValueSeparator)
key to value
}
Slightly more permissive, but simpler (using trim for the brackets):
selection.trim('[', ']')
.split(entrySeparator)
.associate {
val (key, value) = it.split(keyValueSeparator)
key to value
}
But if you're using regex anyway, you may as well use Regex.findAll
, it might be simpler in the endLuke
11/19/2021, 4:46 PM"(\\w+) *= *(\\w+)".toRegex()
.findAll(selection)
.associate { match ->
match.groupValues[1] to match.groupValues[2]
}
It seems to work but I didn't test muchJoffrey
11/19/2021, 4:49 PMAyfri
11/19/2021, 4:50 PMLuke
11/19/2021, 4:51 PM\\w
matches underscore as well if my memory is correctAyfri
11/19/2021, 4:52 PM