Challenge - 5 Problems
Regex Mastery in Kotlin
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin Regex match?
Consider the following Kotlin code snippet. What will be printed when it runs?
Kotlin
val regex = Regex("\\d{3}-\\d{2}-\\d{4}") val input = "My number is 123-45-6789" println(regex.containsMatchIn(input))
Attempts:
2 left
💡 Hint
The regex looks for a pattern of digits separated by dashes matching a social security number format.
✗ Incorrect
The Regex pattern matches exactly three digits, a dash, two digits, a dash, and four digits. The input string contains "123-45-6789" which matches this pattern, so containsMatchIn returns true.
❓ Predict Output
intermediate2:00remaining
What does this Kotlin Regex replace produce?
What is the output of this Kotlin code?
Kotlin
val regex = Regex("cat|dog") val text = "I have a cat and a dog." val result = regex.replace(text, "pet") println(result)
Attempts:
2 left
💡 Hint
The regex matches either "cat" or "dog" and replaces all matches.
✗ Incorrect
The regex matches both "cat" and "dog" in the text. The replace function replaces all matches with "pet", so both words are replaced.
❓ Predict Output
advanced2:00remaining
What is the output of this Kotlin Regex findAll usage?
What will this Kotlin code print?
Kotlin
val regex = Regex("\\b\w{4}\b") val text = "This test code finds four letter words." val matches = regex.findAll(text).map { it.value }.toList() println(matches)
Attempts:
2 left
💡 Hint
The regex looks for exactly 4-letter words using word boundaries.
✗ Incorrect
The regex matches words with exactly 4 letters. "This", "test", "code", and "four" are 4-letter words. "find" has 4 letters but is followed by 's' in "finds", so it doesn't match as a whole word. "word" is 4 letters but appears as "words" (5 letters).
❓ Predict Output
advanced2:00remaining
What error does this Kotlin Regex code raise?
What error will this Kotlin code produce when run?
Kotlin
val regex = Regex("[A-Z+") val text = "Hello" println(regex.matches(text))
Attempts:
2 left
💡 Hint
Check if the regex pattern is valid.
✗ Incorrect
The regex pattern "[A-Z+" is missing a closing bracket for the character class, causing a PatternSyntaxException at runtime.
🧠 Conceptual
expert2:00remaining
How many matches does this Kotlin Regex find?
Given the Kotlin code below, how many matches will be found?
Kotlin
val regex = Regex("(?<=\\s)\d+(?=\\s)") val text = " 123 4567 89 " val matches = regex.findAll(text).count() println(matches)
Attempts:
2 left
💡 Hint
Look carefully at the lookbehind and lookahead requiring spaces around digits.
✗ Incorrect
The regex matches digits that have a space before and after. "123" and "4567" are surrounded by spaces, so they match. "89" is followed by a space but preceded by '7' (no space), so it does not match. Hence, 2 matches.