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: From Basics to Advanced Techniques



Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on a pattern. In Kotlin, working with regular expressions is implemented through the Regex class, which provides a rich API for all standard operations. In this article, we will cover the syntax, main functions, and practical examples of using regular expressions in Kotlin.



1. Creating and Basic Syntax of Regex in Kotlin



In Kotlin, a regular expression is created using the Regex class or via the .toRegex() extension for strings. All standard metacharacters and quantifiers are supported.



Ways to create a Regex:

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

// Method 2: via toRegex()val pattern = "[a-z]+@[a-z]+\\\\.[a-z]+".toRegex()

// Method 3: with options (case-insensitive)val caseInsensitive = Regex("kotlin", RegexOption.IGNORE_CASE)


Basic metacharacters and quantifiers:

  • . — any character (except newline)
  • \\d — digit (0-9)
  • \\w — letter, digit, or underscore
  • \\s — whitespace character
  • ^ — start of string
  • $ — end of string
  • * — 0 or more repetitions
  • + — 1 or more repetitions
  • ? — 0 or 1 repetition
  • {n,m} — from n to m repetitions


2. Basic Operations: Searching, Checking, and Extracting



The Regex class provides several methods for working with text. Let's look at the most important ones.



Checking for a match (matches)

The matches() method checks if the entire string fully matches the pattern:

val phonePattern = Regex("\\\\+7\\\\d{10}")println(phonePattern.matches("+79261234567")) // trueprintln(phonePattern.matches("+7926123456")) // false (9 digits instead of 10)


Finding the first match (find)

The find() method returns the first match as a MatchResult? object:

val text = "Contacts: email@test.com and support@domain.org"val emailRegex = "[\\\\w.]+@[\\\\w.]+\\\\.[a-z]+".toRegex()val match = emailRegex.find(text)println(match?.value) // email@test.comprintln(match?.range) // 10..23 (start and end indices)


Finding all matches (findAll)

To get all matches, use findAll(), which returns a Sequence<MatchResult>:

val allMatches = emailRegex.findAll(text)allMatches.forEach { match ->    println("Found: ${match.value} at position ${match.range.first}")}// Output:// Found: email@test.com at position 10// Found: support@domain.org at position 28


Checking for existence (containsMatchIn)

The containsMatchIn() method returns a Boolean — whether there is at least one match:

val hasEmail = emailRegex.containsMatchIn(text)println(hasEmail) // true


3. Replacement and split using Regex



Regular expressions are great for replacing parts of a string and splitting text.



Replacing the first match (replaceFirst)

val original = "ID: 12345, code: 67890"val digitRegex = "\\\\d+".toRegex()val masked = digitRegex.replaceFirst(original, "***")println(masked) // ID: ***, code: 67890


Replacing all matches (replace)

val censored = digitRegex.replace(original, "***")println(censored) // ID: ***, code: ***


Replacement using a lambda

You can pass a lambda that will be called for each match

Blogs

Book Recommendations