Computer scienceProgramming languagesKotlinAdditional instrumentsRegex

MatchResult and capturing groups

Key-value pairs

Report a typo

You have a Kotlin program that extracts key-value pairs from a single line of input text and prints them as a map. Each key-value pair in the input is separated by a comma and a space; the key is separated from the value by a colon and a space.

fun main() {
    val regex = """(?<key>\w+): (?<value>[^,]+)""".toRegex()
    val input = readln()

    printMap(regex, input)
}

Your task is to implement the printMap function. This function should take a Regex object and a String as input; find all the key-value pairs in the input String; add them to a map; and print the map.

  • Constraints:

    • The keys will consist of one or more word characters (letters, digits, and underscores).

    • The values will consist of one or more characters and will not contain commas.

    • Assume the input string is well-formed and follows the key-value pair format described.

Sample Input 1:

username: user123, age: 42, role: admin

Sample Output 1:

{username=user123, age=42, role=admin}
Write a program in Kotlin
fun printMap(regex: Regex, input: String) {
// Your code goes here
}

Create a free account to access the full topic