0
0
Kotlinprogramming~10 mins

Regular expressions with Regex class in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a Regex object that matches the word "cat".

Kotlin
val pattern = Regex([1])
println(pattern.matches("cat"))
Drag options to blanks, or click blank then click option'
A"cat"
B"dog"
C"bat"
D"rat"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the pattern inside quotes.
Using a wrong pattern string.
2fill in blank
medium

Complete the code to check if the string "hello123" contains digits using Regex.

Kotlin
val regex = Regex([1])
println(regex.containsMatchIn("hello123"))
Drag options to blanks, or click blank then click option'
A"[a-z]+"
B"\\d+"
C"[A-Z]+"
D"\\w+"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a pattern that matches only letters.
Not escaping the backslash properly.
3fill in blank
hard

Fix the error in the code to find all words starting with 'a' in the text.

Kotlin
val text = "apple banana apricot avocado"
val regex = Regex([1])
val matches = regex.findAll(text).map { it.value }.toList()
println(matches)
Drag options to blanks, or click blank then click option'
A"a+"
B"a*"
C"a\\w*"
D"a?"
Attempts:
3 left
💡 Hint
Common Mistakes
Using "a*" which matches zero or more 'a's anywhere.
Using "a+" which requires at least one 'a' but not the following letters.
4fill in blank
hard

Fill both blanks to create a Regex that matches email addresses and test it on a sample string.

Kotlin
val emailRegex = Regex([1])
val testEmail = "user@example.com"
println(emailRegex.[2](testEmail))
Drag options to blanks, or click blank then click option'
A"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"
Bmatches
CcontainsMatchIn
Dfind
Attempts:
3 left
💡 Hint
Common Mistakes
Using containsMatchIn() which checks partial matches.
Using an incomplete regex pattern.
5fill in blank
hard

Fill all three blanks to extract all numbers from a string and convert them to integers.

Kotlin
val input = "I have 2 apples and 10 bananas"
val numberRegex = Regex([1])
val numbers = numberRegex.findAll(input).map { it.[2].to[3]() }.toList()
println(numbers)
Drag options to blanks, or click blank then click option'
A"\\d+"
Bvalue
CInt
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text' instead of 'value' to get the matched string.
Forgetting to convert the string to Int.