Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Regular Expressions (Regex) are powerful tools for text processing. They provide a means to search, match, and manipulate text. Kotlin, like many programming languages, has built-in support for regular expressions, and it's pretty easy to use once you get the hang of it.
In Kotlin, you can create a Regex
object by invoking the toRegex()
function on a string:
val regex = "\\d+".toRegex() // Matches one or more digits
Or you can use the Regex
constructor directly:
val regex = Regex("\\d+")
Use the matches
function to check if an entire string matches a given regex:
val isMatch = regex.matches("12345") // true
To find occurrences of a pattern within a string, use the find
or findAll
functions:
val result = regex.find("abc123def456") println(result?.value) // Outputs: 123 val allResults = regex.findAll("abc123def456") for (match in allResults) { println(match.value) // Outputs: 123 and then 456 }
You can group parts of your regex pattern using parentheses. This can be useful to extract specific portions of a match:
val pattern = "(\\d+)-(\\d+)".toRegex() val match = pattern.matchEntire("123-456") if (match != null) { println(match.groupValues[1]) // Outputs: 123 println(match.groupValues[2]) // Outputs: 456 }
To replace occurrences of the regex pattern in a string, use the replace
function:
val result = "\\d+".toRegex().replace("abc123def456", "X") println(result) // Outputs: abcXdefX
You can also use matched groups in the replacement:
val result = "(\\d+)-(\\d+)".toRegex().replace("123-456", "$2-$1") println(result) // Outputs: 456-123
To split a string based on a regex pattern, use the split
function:
val parts = "\\s+".toRegex().split("One Two Three") println(parts) // Outputs: [One, Two, Three]
.
: Matches any single character (except newline).^
: Matches the beginning of a line or string.$
: Matches the end of a line or string.*
: Matches 0 or more of the preceding token.+
: Matches 1 or more of the preceding token.?
: Matches 0 or 1 of the preceding token.{n}
: Matches exactly n
of the preceding token.{n,}
: Matches n
or more of the preceding token.{n,m}
: Matches between n
and m
of the preceding token.\\d
: Matches any digit, equivalent to [0-9]
.\\D
: Matches any non-digit.\\w
: Matches any word character (alphanumeric and underscore).\\W
: Matches any non-word character.\\s
: Matches any whitespace character (spaces, tabs, line breaks).Regular expressions in Kotlin are straightforward to use and very powerful. They provide a flexible way to search, manipulate, and validate strings. It's worth noting, however, that complex regular expressions can become hard to read and maintain, so always make sure to comment and document your regex patterns.
Regex pattern matching in Kotlin:
val pattern = "Kotlin".toRegex() val isMatch = pattern.matches("Kotlin is awesome!")
Creating regex patterns in Kotlin:
val customPattern = Regex("[0-9]{3}-[0-9]{2}")
Using the Regex class in Kotlin:
Regex
class for regex operations.val regex = Regex("[a-zA-Z]+") val matches = regex.findAll("Hello Kotlin, meet Regex")
Matching and extracting groups in Kotlin regex:
val regexWithGroups = Regex("(\\d+)-(\\d+)") val result = regexWithGroups.find("Age: 25-30")?.groupValues
Regex options and flags in Kotlin:
val caseInsensitiveRegex = Regex("kotlin", RegexOption.IGNORE_CASE)
Working with quantifiers in Kotlin regex:
val repeatedPattern = Regex("a{2,4}")
Character classes and ranges in Kotlin regex:
val charClassRegex = Regex("[A-Za-z0-9]")
Anchors and boundaries in Kotlin regex:
val startOfStringRegex = Regex("^Kotlin")
Regex metacharacters in Kotlin:
val specialCharRegex = Regex("\\d{3}[-\\.\\s]\\d{2}")
Replacing and manipulating strings with regex in Kotlin:
val replacedString = "Replace digits: 12345".replace(Regex("\\d+"), "X")
Validating input with regex in Kotlin:
val emailRegex = Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}") val isValidEmail = emailRegex.matches("user@example.com")
Regex and Kotlin's string interpolation:
val dynamicPattern = Regex("${userInput}\\d{3}")