Regular Expressions in Kotlin: Complete Guide with Examples

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: A Complete Guide with Examples



Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on patterns. In Kotlin, working with regex is implemented through the Regex class, which provides a convenient API and full compatibility with the Java implementation java.util.regex.Pattern. In this article, we will cover all aspects of using regular expressions in Kotlin with clear examples.



1. Creating and Basic Usage of Regex in Kotlin



In Kotlin, there are two main ways to create a regular expression:



  • The Regex class constructor — you pass a string with the pattern.
  • The .toRegex() extension method — called on a string.


Examples of creation:



// Method 1: constructorval regex1 = Regex("\\\\d{3}-\\\\d{2}-\\\\d{4}")

// Method 2: toRegex()val regex2 = "\\\\d{3}-\\\\d{2}-\\\\d{4}".toRegex()

// With flags (case-insensitive search)val regex3 = Regex("hello", RegexOption.IGNORE_CASE)

// Multiline modeval regex4 = Regex("^start", RegexOption.MULTILINE)


Note: in Kotlin, as in Java, a double backslash \\\\ is used to escape the backslash. If you write \\d, you need to write "\\\\d".



2. Main Regex Functions: Checking, Searching, Replacing



The Regex class provides several key functions for working with strings.



2.1. Checking for a Full Match — matches()



The matches() function returns true if the entire string matches the pattern.



val emailRegex = Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}")

val email1 = "user@example.com"val email2 = "invalid-email"

println(emailRegex.matches(email1)) // trueprintln(emailRegex.matches(email2)) // false


2.2. Finding the First Match — find()



Returns the first found match as a MatchResult? object (or null if nothing is found).



val text = "My phone: 123-45-6789 and also 987-65-4321"val phoneRegex = Regex("\\\\d{3}-\\\\d{2}-\\\\d{4}")

val firstMatch = phoneRegex.find(text)if (firstMatch != null) { println("Found phone: ${firstMatch.value}") // Found phone: 123-45-6789 println("Start: ${firstMatch.range.first}") // Start: 10}


2.3. Finding All Matches — findAll()



Returns a Sequence<MatchResult> of all non-overlapping matches.



val text = "Prices: 100 rub., 250 rub., 50 rub."val priceRegex = Regex("\\\\d+")

val prices = priceRegex.findAll(text)prices.forEach { match -> println("Price: ${match.value}")}// Output:// Price: 100// Price: 250// Price: 50


2.4. Pattern-Based Replacement — replace()



The replace() function replaces all found matches with a specified string or the result of a lambda expression.



val text = "My email: john@mail.com and support@site.org"val emailRegex = Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}")

// Simple replacementval masked = emailRegex.replace(text, "[EMAIL HIDDEN]")println(masked) // My email: [EMAIL HIDDEN] and [EMAIL HIDDEN]

// Replacement with lambda (dynamic)val replaced = emailRegex.replace(text) { match -> val local = match.value.split("@")[0] "${local.first()}***@***"}println(replaced) // My email: j***@*** and s***@***


2.5. Splitting a String — split()



Splits a string by matches with the regular expression.



val text = "apple,pear;banana|orange"val separators = Regex("[,;|]")

val fruits = separators.split(text)println(fru

Blogs

Book Recommendations