kotlinbeginner

Kotlin Regex Pattern Matching

Use Kotlin regex for validation, extraction, replacing, and destructuring with named groups.

kotlin
fun main() {
    // Create regex
    val emailRegex = """[\w.+-]+@[\w-]+\.[\w.]+""".toRegex()
    val phoneRegex = """\+?\d{1,4}[-.\s]?\(?\d{1,3}\)?[-.\s]?\d{3,4}[-.\s]?\d{4}""".toRegex()

    // Validate
    println(emailRegex.matches("alice@test.com")) // true
    println(emailRegex.matches("invalid"))        // false

    // Find first match
    val text = "Contact alice@test.com or bob@example.org"
    val first = emailRegex.find(text)
    println("First: ${first?.value}") // alice@test.com

    // Find all matches
    val allEmails = emailRegex.findAll(text).map { it.value }.toList()
    println("All: $allEmails")

    // Named groups
    val logRegex = """\[(?<ts>[^]]+)] (?<level>\w+) (?<msg>.+)""".toRegex()
    val log = "[2024-01-15 10:30:00] ERROR Database connection failed"
    logRegex.find(log)?.let { match ->
        println("Time:  ${match.groups["ts"]?.value}")
        println("Level: ${match.groups["level"]?.value}")
        println("Msg:   ${match.groups["msg"]?.value}")
    }

    // Destructuring
    val dateRegex = """(\d{4})-(\d{2})-(\d{2})""".toRegex()
    dateRegex.find("2024-03-15")?.destructured?.let { (year, month, day) ->
        println("Year=$year, Month=$month, Day=$day")
    }

    // Replace with transform
    val masked = emailRegex.replace(text) { match ->
        val email = match.value
        val at = email.indexOf('@')
        "${email[0]}***${email.substring(at)}"
    }
    println("Masked: $masked")

    // Split
    val csv = "apple, banana ,cherry,  date"
    val items = csv.split(",\\s*".toRegex())
    println("Items: $items")

    // containsMatchIn
    val hasNumber = "\\d+".toRegex()
    println("Has number: ${hasNumber.containsMatchIn("abc123")}")
}

Use Cases

  • Input validation for forms and APIs
  • Log parsing with named capture groups
  • Text extraction and transformation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.