Kotlin: parsing a list of pairs delimited by parentheses into a list of Pairs()

Viewed 304

I haven't figured out how to use the Kotlin split function to parse this series of edges into a List of Pairs.

(2, 4), (3, 6), (5, 1), (8, 9), (10, 12), (11, 7)

I could write a character by character parser with no problem - but it there a Kotlin solution to this parsing problem?

2 Answers

Aleksei's answer should work fine, although it doesn't give you numbers.

Also, I'd rather write it this way (broken down into functions):

private fun String.parsePairs(): List<Pair<Int, Int>> = removePrefix("(")
    .removeSuffix(")")
    .split("), (")
    .map { it.parsePair() }

private fun String.parsePair(): Pair<Int, Int> =
    split(", ").let { it[0].toInt() to it[1].toInt() }

Another option is to use regex. It's a bit overkill here, but more general in case you have more complex requirements:

val regex = Regex("""\((\d+),\s*(\d+)\)""")

private fun String.parsePairs(): List<Pair<Int, Int>> = regex.findAll(this)
        .map { it.groupValues[1].toInt() to it.groupValues[2].toInt() }
        .toList()
s.substring(1, s.length-1)
    .split("), (")
    .map { it.split(", ") }
    .map { it[0] to it[1] }
Related