0
0
Kotlinprogramming~20 mins

Regular expressions with Regex class in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Mastery in Kotlin
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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))
Afalse
Btrue
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
The regex looks for a pattern of digits separated by dashes matching a social security number format.
Predict Output
intermediate
2: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)
AI have a pet and a pet.
BI have a cat and a dog.
CI have a pet and a dog.
DI have a cat and a pet.
Attempts:
2 left
💡 Hint
The regex matches either "cat" or "dog" and replaces all matches.
Predict Output
advanced
2: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)
A[This, test, code, find, four, word]
B[This, test, code, find, four, word, words]
C[This, test, code, four]
D[This, test, code]
Attempts:
2 left
💡 Hint
The regex looks for exactly 4-letter words using word boundaries.
Predict Output
advanced
2: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))
Ajava.util.regex.PatternSyntaxException
BNo error, prints false
CNo error, prints true
DNullPointerException
Attempts:
2 left
💡 Hint
Check if the regex pattern is valid.
🧠 Conceptual
expert
2: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)
A0
B1
C3
D2
Attempts:
2 left
💡 Hint
Look carefully at the lookbehind and lookahead requiring spaces around digits.