Kotlin Regex

Regular expressions (regex) are patterns used to search, match, and transform text. Kotlin provides a clean Regex class that wraps Java's regex engine. Use regex when simple string functions like contains or split are not flexible enough.

Creating a Regex

// Two ways to create a Regex
val pattern1 = Regex("\\d+")           // matches one or more digits
val pattern2 = """\d+""".toRegex()     // raw string — no double backslash needed

// Raw strings (triple quotes) are preferred for regex — they are easier to read
val emailPattern = """[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}""".toRegex()

Common Regex Symbols


Symbol  │ Meaning                    │ Example
────────┼────────────────────────────┼──────────────────
\d      │ digit (0-9)                │ \d+ → "123"
\w      │ word char (a-z, A-Z, 0-9)  │ \w+ → "hello"
\s      │ whitespace                 │ \s+ → "   "
.       │ any character              │ a.c → "abc", "a1c"
^       │ start of string            │ ^Hello → starts with Hello
$       │ end of string              │ .com$ → ends with .com
*       │ zero or more               │ ab* → "a", "ab", "abb"
+       │ one or more                │ \d+ → "1", "12", "123"
?       │ zero or one                │ colou?r → "color", "colour"
{n}     │ exactly n times            │ \d{4} → "2024"
{n,m}   │ between n and m times      │ \d{2,4} → "12", "123"
[abc]   │ any of a, b, c             │ [aeiou] → vowels
[^abc]  │ none of a, b, c            │ [^\d] → non-digit
(...)   │ group                      │ (ab)+ → "ab", "abab"
a|b     │ a or b                     │ cat|dog → "cat" or "dog"

Matching

val phone = """\d{10}""".toRegex()

println(phone.matches("9876543210"))   // true  — entire string matches
println(phone.matches("987654321"))    // false — only 9 digits
println(phone.matches("98765432101"))  // false — 11 digits

val anyDigit = """\d+""".toRegex()
println(anyDigit.containsMatchIn("Order #1042 placed"))  // true
println(anyDigit.containsMatchIn("No numbers here"))     // false

Finding Matches

val text = "Call us at 9876543210 or 8765432109 for support"
val phoneRegex = """\d{10}""".toRegex()

// First match only
val first = phoneRegex.find(text)
println(first?.value)   // 9876543210

// All matches
val all = phoneRegex.findAll(text)
all.forEach { println(it.value) }
// 9876543210
// 8765432109

Capturing Groups

val dateRegex = """(\d{4})-(\d{2})-(\d{2})""".toRegex()
val date = "Event date: 2024-06-15"

val match = dateRegex.find(date)
if (match != null) {
    val (year, month, day) = match.destructured
    println("Year=$year, Month=$month, Day=$day")
}

Output:

Year=2024, Month=06, Day=15

Replace with Regex

val text = "My card: 4111-1111-1111-1111 and pin: 9876"

// Replace digits in card number with *
val masked = """\d""".toRegex().replace(text, "*")
println(masked)   // My card: ****-****-****-**** and pin: ****

// Replace only first match
val partial = """\d{4}""".toRegex().replaceFirst(text, "****")
println(partial)  // My card: ****-1111-1111-1111 and pin: 9876

Split with Regex

val csv = "apple , banana,  cherry,date"

// Split on comma with optional surrounding spaces
val fruits = """\s*,\s*""".toRegex().split(csv)
println(fruits)   // [apple, banana, cherry, date]

val sentence = "one  two   three    four"
val words = """\s+""".toRegex().split(sentence)
println(words)    // [one, two, three, four]

Regex Options

val ci = Regex("kotlin", RegexOption.IGNORE_CASE)
println(ci.containsMatchIn("I love KOTLIN"))   // true
println(ci.containsMatchIn("I love Java"))     // false

val multi = Regex("^line", RegexOption.MULTILINE)
val block = "line one\nline two\nother"
println(multi.findAll(block).count())   // 2

Practical Example: Input Validator

object Validator {
    val email    = """^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$""".toRegex()
    val phone    = """^\+?[0-9]{10,13}$""".toRegex()
    val password = """^(?=.*[A-Z])(?=.*\d).{8,}$""".toRegex()  // 1 upper, 1 digit, 8+ chars
    val pincode  = """^\d{6}$""".toRegex()

    fun validate(label: String, value: String, pattern: Regex) {
        val status = if (pattern.matches(value)) "✓ valid" else "✗ invalid"
        println("$label '$value' → $status")
    }
}

fun main() {
    Validator.validate("Email",    "alice@mail.com",  Validator.email)
    Validator.validate("Email",    "notanemail",       Validator.email)
    Validator.validate("Phone",    "+919876543210",    Validator.phone)
    Validator.validate("Password", "Secret1!",         Validator.password)
    Validator.validate("Password", "weak",             Validator.password)
    Validator.validate("Pincode",  "400001",           Validator.pincode)
}

Output:

Email 'alice@mail.com' → ✓ valid
Email 'notanemail' → ✗ invalid
Phone '+919876543210' → ✓ valid
Password 'Secret1!' → ✓ valid
Password 'weak' → ✗ invalid
Pincode '400001' → ✓ valid

Leave a Comment

Your email address will not be published. Required fields are marked *