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.
0
0
Regular expressions with Regex class in Kotlin
Introduction
You want to check if a phone number is in the right format.
You need to find all email addresses in a block of text.
You want to replace all spaces with dashes in a string.
You want to split a sentence into words based on punctuation.
You want to validate if a password contains certain characters.
Syntax
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.
Examples
This finds the first group of digits in the text and prints it.
Kotlin
val regex = Regex("\\d+") val text = "There are 123 apples" println(regex.find(text)?.value)
This finds all words made of letters and prints them as a list.
Kotlin
val regex = Regex("[a-zA-Z]+") val text = "Hello 123 World" val words = regex.findAll(text).map { it.value }.toList() println(words)
This replaces all occurrences of "cat" with "dog" in the text.
Kotlin
val regex = Regex("cat") val text = "The cat sat on the cat mat" val replaced = regex.replace(text, "dog") println(replaced)
Sample Program
This program finds all words with exactly 4 letters in the given text and prints them as a list.
Kotlin
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") }
OutputSuccess
Important Notes
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.
Summary
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.