Using regular expressions

Kotlin:
Using regular expressions

How to:

Basic Matching

To check if a string matches a specific pattern in Kotlin, you can use the matches method of the Regex class.

val pattern = "kotlin".toRegex()
val input = "I love kotlin"
val result = pattern.containsMatchIn(input)

println(result)  // Output: true

Finding and Extracting Parts of String

If you want to find parts of a string that match a pattern, Kotlin allows you to iterate over all matches:

val datePattern = "\\d{2}/\\d{2}/\\d{4}".toRegex()
val input = "Today's date is 07/09/2023."
val dates = datePattern.findAll(input)

for (date in dates) {
    println(date.value)
}
// Output: 07/09/2023

Replacing Text

Replacing parts of a string that match a pattern is straightforward with the replace function:

val input = "Username: user123"
val sanitizedInput = input.replace("\\d+".toRegex(), "XXX")

println(sanitizedInput)  // Output: Username: userXXX

Splitting Strings

Split a string into a list, using a regex pattern as the delimiter:

val input = "1,2,3,4,5"
val numbers = input.split(",".toRegex())

println(numbers)  // Output: [1, 2, 3, 4, 5]

Third-Party Libraries: Kotest

Kotest is a popular Kotlin testing library that extends Kotlin’s built-in regex support, particularly useful for validation in test cases.

// Assuming Kotest is added to your project
import io.kotest.matchers.string.shouldMatch

val input = "[email protected]"
input shouldMatch "\\S+@\\S+\\.com".toRegex()

// This will pass the test if the input matches the email pattern.

By incorporating regular expressions into your Kotlin applications, you can perform sophisticated text processing efficiently. Whether you’re validating user input, extracting data, or transforming strings, regex patterns offer a robust solution.