Hi, I have a string (named `selection`) that is eq...
# getting-started
a
Hi, I have a string (named
selection
) 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 ?
Copy code
val attributes = selection.replace("[(\\w+)]".toRegex(), "$1").replace("\\s+".toRegex(), "").split(',').associate { it.substringBefore('=') to it.substringAfter('=') }
j
In the same vein, but a bit clearer IMO (it doesn't clear the spaces inside keys and values):
Copy code
// 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):
Copy code
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 end
l
I got this:
Copy code
"(\\w+) *= *(\\w+)".toRegex()
    .findAll(selection)
    .associate { match ->
        match.groupValues[1] to match.groupValues[2]
    }
It seems to work but I didn't test much
j
Yeah the regex will depend on what can be a key/value
a
only text & numbers can be key/value, so \\w+ is valid
l
\\w
matches underscore as well if my memory is correct
My snippet accepts it on jvm at least
a
Yeah it works nicely, thank you all !
👍 1