Sling Academy
Home/Kotlin/Matching Strings with Regular Expressions in Kotlin

Matching Strings with Regular Expressions in Kotlin

Last updated: November 30, 2024

Regular expressions, often abbreviated as regex, are sequences of characters that define search patterns. They are an incredibly powerful tool for string matching and manipulation. Kotlin, being an evolution of Java, inherits the rich functionalities of regular expressions and offers a more idiomatic way to handle them.

Introduction to Regular Expressions in Kotlin

Kotlin natively supports regular expressions and provides a very user-friendly way to work with them. The Regex class in Kotlin is the core of regular expression functionalities and offers numerous utilities to perform operations like search, search-and-replace, and validation.

Basic Usage

You can create a regular expression by calling the Regex() constructor with a regex pattern as a String. Here's a basic example:

val regex = Regex("\\d+") // Matches one or more digits

Once you have a Regex object, you can use it to search within a string.

val matches = regex.findAll("There are 123 apples and 456 bananas.")
for (match in matches) {
    println(match.value)
}
// Output:
// 123
// 456

Matching Exact Patterns

To check if a string completely matches a regular expression, use the matches() function:

val exactMatchRegex = Regex("a+b+")
println(exactMatchRegex.matches("aabb")) // true
println(exactMatchRegex.matches("aababc")) // false

Using Regex with String functions

Kotlin also enhances the usage of regular expressions by integrating regex functionalities within the String class itself.

val input = "The rain in Spain stays mainly in the plain."

// Check if the input contains a certain pattern
println(input.contains(Regex("ain"))) // true

// Replace sequences with another string
val replaced = input.replace(Regex("ain"), "XYZ")
println(replaced)
// Output: "The rXYZ in SpXYZ stays mXYZly in the plXYZ."

Regular Expression Groups

Groups allow you to match parts of the regex and access them later. Groups are created by wrapping parts of the regex pattern in parentheses.

val dateRegex = Regex("(\\d{2})-(\\d{2})-(\\d{4})")
val matchResult = dateRegex.find("Today's date is 25-12-2023.")

if (matchResult != null) {
    val (day, month, year) = matchResult.destructured
    println("Day: $day, Month: $month, Year: $year")
    // Output: Day: 25, Month: 12, Year: 2023
}

Advanced Features

Kotlin provides several other functions for advanced regular expression handling, including checking match results, replacing patterns conditionally, and more. Here's an example of using replace with a lambda:

val text = "The amount is -200 or 300."
val balance = Regex("-\\d+")

val adjustedText = balance.replace(text) {
    val number = it.value.toInt()
    "(${number * -1})"
}
println(adjustedText) 
// Output: "The amount is (200) or 300."

Conclusion

Regular expressions in Kotlin elevate string processing to a new level. With concise syntax and integrated support via the Regex class and String methods, regular expressions become a potent tool in a Kotlin developer's toolkit. Practice writing and applying various regex patterns to become more proficient in using this powerful language feature.

Next Article: Using Regex to Validate Email Addresses in Kotlin

Previous Article: How to Create and Use Regex Patterns in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin