Regular expressions help you find patterns in text quickly. The Regex class in Kotlin makes it easy to search, match, and replace text using these patterns.
Regular expressions with Regex class in Kotlin
val regex = Regex("pattern") // Check if text matches pattern val result = regex.matches("text") // Find first match val match = regex.find("text") // Find all matches val matches = regex.findAll("text") // Replace matches val replaced = regex.replace("text", "replacement")
The pattern is a string that describes what you want to find.
Use double backslashes \\ in the pattern to escape special characters.
val regex = Regex("\\d+") val text = "There are 123 apples" println(regex.find(text)?.value)
val regex = Regex("[a-zA-Z]+") val text = "Hello 123 World" val words = regex.findAll(text).map { it.value }.toList() println(words)
val regex = Regex("cat") val text = "The cat sat on the cat mat" val replaced = regex.replace(text, "dog") println(replaced)
This program finds all words with exactly 4 letters in the given text and prints them as a list.
fun main() { val regex = Regex("\\b\\w{4}\\b") // words with exactly 4 letters val text = "This test will find four letter words like test and find" val matches = regex.findAll(text).map { it.value }.toList() println("Four letter words found: $matches") }
Regex patterns can be tricky at first; try simple patterns and test often.
Use online regex testers to experiment with patterns before coding.
The Regex class methods like findAll return sequences, so convert to list to see all matches.
Regex class helps find and work with text patterns easily.
Use matches, find, findAll, and replace methods for common tasks.
Patterns use special symbols; escape them properly in Kotlin strings.
Practice
Regex.matches() function do in Kotlin?Solution
Step 1: Understand Regex.matches() purpose
Thematches()function returns true only if the whole input string fits the pattern exactly.Step 2: Differentiate from other Regex methods
Other methods likefind()look for parts of the string, butmatches()requires full match.Final Answer:
Checks if the entire input string matches the regex pattern -> Option DQuick Check:
matches() = full string match [OK]
- Thinking matches() finds partial matches
- Confusing matches() with find()
- Assuming matches() replaces text
Solution
Step 1: Understand escaping in Kotlin strings
In Kotlin, backslash must be escaped, so to represent \d (digit), we write "\\d".Step 2: Check the quantifier usage
"\\d+" means one or more digits, which is correct for matching digits.Final Answer:
val regex = Regex("\\d+") -> Option AQuick Check:
Double backslash needed for \d in Kotlin strings [OK]
- Using single backslash without escaping
- Confusing character class syntax
- Missing quantifier '+' for multiple digits
val regex = Regex("a.b")
val input = "acb aab aeb"
val matches = regex.findAll(input).map { it.value }.toList()
println(matches)Solution
Step 1: Understand the regex pattern "a.b"
The dot '.' matches any single character, so "a.b" matches 'a' + any char + 'b'.Step 2: Check input string matches
Input has "acb", "aab", and "aeb" all matching the pattern.Final Answer:
["acb", "aab", "aeb"] -> Option AQuick Check:
Dot matches any char between 'a' and 'b' [OK]
- Thinking dot matches zero or multiple chars
- Missing some matches in the list
- Confusing findAll with matches
val regex = Regex("[a-z")
val result = regex.matches("abc")Solution
Step 1: Check regex pattern syntax
The pattern "[a-z" has an opening square bracket but no closing bracket, causing a syntax error.Step 2: Understand consequences
Regex constructor will throw an exception due to invalid pattern.Final Answer:
Unclosed character class in regex pattern -> Option BQuick Check:
Character classes must be closed with ']' [OK]
- Forgetting to close square brackets
- Thinking matches() needs raw strings
- Confusing escape rules for brackets
Solution
Step 1: Choose correct regex pattern for spaces
"\\s+" matches one or more whitespace characters; correct for sequences of spaces.Step 2: Use correct Kotlin Regex method
Kotlin's Regex class usesreplace()to replace all matches;replaceAll()does not exist.Final Answer:
Regex("\\s+").replace(input, "-") -> Option CQuick Check:
Use replace() with "\\s+" to replace spaces [OK]
- Using replaceAll() which is not in Kotlin Regex
- Using "\\s*" which matches zero spaces
- Not escaping backslash properly
Ready to prove it?
Pass the test and this pattern moves unknown
