kotlinbeginner
Kotlin Regex Pattern Matching
Use Kotlin regex for validation, extraction, replacing, and destructuring with named groups.
kotlinPress ⌘/Ctrl + Shift + C to copy
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.
kotlinintermediate
Regex — Match, Replace, and Extract
Use Kotlin regex for pattern matching: find, replace, named groups, and structured extraction.
Best for: Log file parsing and analysis
#kotlin#regex
javaintermediate
Java Regex — Pattern Matching Examples
Common regex patterns with Pattern and Matcher: email, URL, phone, extraction, and replacement.
Best for: Input validation for emails, URLs, and phone numbers
#java#regex
kotlinbeginner
Preconditions — require, check, and error
Validate inputs and state with Kotlin preconditions: require, check, error, and custom assertions.
Best for: Input validation at function boundaries
#kotlin#validation
kotlinintermediate
Kotlin Error Handling Patterns
Comprehensive error handling: sealed result types, validated aggregation, and railway-oriented programming.
Best for: Form validation with error accumulation
#kotlin#error-handling