Regular Expressions in Kotlin with Examples: In Practice

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in Kotlin with Examples: In Practice



Regular expressions (regex) are a powerful tool for working with text, allowing you to search, replace, and validate strings based on a pattern. In Kotlin, working with regular expressions is implemented through the Regex class and a set of convenient extension functions. In this article, we will break down the syntax, main methods, and look at practical examples that will help you quickly master regex in Kotlin.



1. Basics of Working with the Regex Class



In Kotlin, a regular expression is created using the Regex class. The pattern can be specified as a string or using a raw string (triple quotes """), which is especially convenient to avoid escaping backslashes.



// Regular stringval pattern1 = Regex("\\\\d+")  // one or more digits

// Raw string (recommended)val pattern2 = Regex("""\\d+""") // same thing, but without escaping


The Regex class also accepts optional flags, for example, RegexOption.IGNORE_CASE for case-insensitive search.



val caseInsensitive = Regex("""hello""", RegexOption.IGNORE_CASE)


2. Main Methods: match, find, replace



Kotlin provides several key methods for working with regular expressions. Let's look at the most popular ones.



2.1. matchEntire method (full match)

Checks whether the entire string matches the pattern. Returns MatchResult? or null.



val regex = Regex("""\\d{3}-\\d{2}-\\d{4}""")val text = "123-45-6789"val matchResult = regex.matchEntire(text)println(matchResult?.value) // Output: 123-45-6789

// If the string does not match the patternval badText = "123-45-678"println(regex.matchEntire(badText)) // Output: null


2.2. find method (first match)

Searches for the first occurrence of the pattern in the string. Returns MatchResult?.



val regex = Regex("""\\d+""")val text = "Price: 150 rubles, discount: 30%"val firstMatch = regex.find(text)println(firstMatch?.value) // Output: 150


2.3. findAll method (all matches)

Finds all non-overlapping occurrences of the pattern. Returns a sequence of MatchResult.



val regex = Regex("""\\d+""")val text = "Price: 150 rubles, discount: 30%"val allMatches = regex.findAll(text)allMatches.forEach { println(it.value) }// Output:// 150// 30


2.4. replace method (replacement)

Replaces all occurrences of the pattern with the specified string or the result of a lambda.



val regex = Regex("""\\d+""")val text = "ID: 12345, code: 67890"val result = regex.replace(text, "***")println(result) // Output: ID: ***, code: ***

// Replacement using a lambda (dynamic replacement)val dynamicResult = regex.replace(text) { matchResult -> "[" + matchResult.value.toInt().toString() + "]"}println(dynamicResult) // Output: ID: [12345], code: [67890]


3. Capturing Groups



Capturing groups allow you to extract parts of a match. In Kotlin, groups can be accessed by index or name (if specified).



3.1. Access by index

val regex = Regex("""(\\d{2})\\.(\\d{2})\\.(\\d{4})""") // date in DD.MM.YYYY formatval text = "Today: 15.03.2024"val match = regex.find(text)if (match != null) {    val (day, month, year) = match.destructured    println("Day: $day, Month: $month, Year: $year")    // Output: Day: 15, Month: 03, Year: 2024}


3.2. Named groups

In Kotlin, you can use named groups (syntax (?<name>...)).



val regex = Regex("""(?<username>\\w+)@(?<domain>\\w+\\.\\w+)""")val text = "email: user@example.com"val match = regex.find(text)if (match != null) {    val username = match.groups["u                

Blogs

Book Recommendations