π Regular Expressions
π What are Regular Expressions?β
Regular Expressions (Regex) are a way to express string patterns. They are used for searching, validation, extraction, and replacement!
π‘ Basic Usageβ
Creating Regexβ
fun main() {
// Create Regex object
val regex1 = Regex("hello")
val regex2 = "hello".toRegex()
// Check matching
println(regex1.matches("hello")) // true
println(regex1.matches("Hello")) // false (case sensitive)
}
Simple Matchingβ
fun main() {
val text = "My email is hong@example.com"
// contains
val hasEmail = Regex("@").containsMatchIn(text)
println(hasEmail) // true
// find
val match = Regex("\\w+@\\w+\\.\\w+").find(text)
println(match?.value) // hong@example.com
}
π― Basic Patternsβ
Character Classesβ
fun main() {
// \d - digits
println("123".matches(Regex("\\d+"))) // true
// \w - word characters (letters, digits, _)
println("hello_123".matches(Regex("\\w+"))) // true
// \s - whitespace
println(" ".matches(Regex("\\s"))) // true
// . - any character
println("abc".matches(Regex("..."))) // true (3 characters)
}
Quantifiersβ
fun main() {
// + : 1 or more
println("aaa".matches(Regex("a+"))) // true
// * : 0 or more
println("".matches(Regex("a*"))) // true
// ? : 0 or 1
println("a".matches(Regex("a?"))) // true
// {n} : exactly n
println("aaa".matches(Regex("a{3}"))) // true
// {n,m} : between n and m
println("aaa".matches(Regex("a{2,4}"))) // true
}
π¨ Practical Examplesβ
Email Validationβ
fun isValidEmail(email: String): Boolean {
val pattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return email.matches(pattern.toRegex())
}
fun main() {
println(isValidEmail("hong@example.com")) // true
println(isValidEmail("invalid.email")) // false
println(isValidEmail("test@domain.co.kr")) // true
}
Phone Number Validationβ
fun isValidPhone(phone: String): Boolean {
// 010-1234-5678 or 01012345678
val pattern = "010-?\\d{4}-?\\d{4}"
return phone.matches(pattern.toRegex())
}
fun main() {
println(isValidPhone("010-1234-5678")) // true
println(isValidPhone("01012345678")) // true
println(isValidPhone("02-1234-5678")) // false
}
Password Strengthβ
fun checkPasswordStrength(password: String): String {
val hasLength = password.length >= 8
val hasDigit = Regex("\\d").containsMatchIn(password)
val hasLower = Regex("[a-z]").containsMatchIn(password)
val hasUpper = Regex("[A-Z]").containsMatchIn(password)
val hasSpecial = Regex("[!@#$%^&*]").containsMatchIn(password)
return when {
hasLength && hasDigit && hasLower && hasUpper && hasSpecial -> "Very Strong"
hasLength && hasDigit && (hasLower || hasUpper) -> "Strong"
hasLength -> "Medium"
else -> "Weak"
}
}
fun main() {
println(checkPasswordStrength("Pass123!")) // Very Strong
println(checkPasswordStrength("password123")) // Strong
println(checkPasswordStrength("password")) // Medium
println(checkPasswordStrength("pass")) // Weak
}
URL Extractionβ
fun extractUrls(text: String): List<String> {
val pattern = "https?://[\\w./]+"
return Regex(pattern).findAll(text).map { it.value }.toList()
}
fun main() {
val text = """
Visit https://kotlin.org for info.
Check http://example.com too!
""".trimIndent()
val urls = extractUrls(text)
urls.forEach { println(it) }
// https://kotlin.org
// http://example.com
}
Hashtag Extractionβ
fun extractHashtags(text: String): List<String> {
val pattern = "#\\w+"
return Regex(pattern).findAll(text).map { it.value }.toList()
}
fun main() {
val tweet = "Beautiful weather today #weather #happiness #kotlin"
val hashtags = extractHashtags(tweet)
println("Hashtags:")
hashtags.forEach { println(it) }
// #weather
// #happiness
// #kotlin
}
π§ Advanced Featuresβ
Group Captureβ
fun parseDate(text: String): Triple<String, String, String>? {
val pattern = "(\\d{4})-(\\d{2})-(\\d{2})"
val match = Regex(pattern).find(text) ?: return null
val (year, month, day) = match.destructured
return Triple(year, month, day)
}
fun main() {
val date = parseDate("Today is 2024-12-25")
if (date != null) {
val (year, month, day) = date
println("Year: $year, Month: $month, Day: $day")
}
}
Replacementβ
fun main() {
val text = "My phone is 010-1234-5678"
// Mask phone number
val masked = text.replace(Regex("\\d{4}$"), "****")
println(masked) // My phone is 010-1234-****
// Multiple spaces to one
val multiSpace = "Hello World !"
val cleaned = multiSpace.replace(Regex("\\s+"), " ")
println(cleaned) // Hello World !
}
Splittingβ
fun main() {
// Split by comma or space
val text = "apple, banana orange,grape"
val fruits = text.split(Regex("[,\\s]+"))
println(fruits) // [apple, banana, orange, grape]
// Split by digits
val text2 = "item1,item2,item3"
val items = text2.split(Regex("\\d+"))
println(items) // [item, ,item, ,item, ]
}
π― Practical Patternsβ
Remove HTML Tagsβ
fun removeHtmlTags(html: String): String {
return html.replace(Regex("<[^>]*>"), "")
}
fun main() {
val html = "<p>Hello <b>World</b>!</p>"
val text = removeHtmlTags(html)
println(text) // Hello World!
}
Extract Numbersβ
fun extractNumbers(text: String): List<Int> {
return Regex("\\d+").findAll(text)
.map { it.value.toInt() }
.toList()
}
fun main() {
val text = "I have 3 apples and 5 oranges"
val numbers = extractNumbers(text)
println(numbers) // [3, 5]
}
Currency Formattingβ
fun formatCurrency(amount: Int): String {
return amount.toString().replace(Regex("(\\d)(?=(\\d{3})+$)"), "$1,")
}
fun main() {
println(formatCurrency(1000)) // 1,000
println(formatCurrency(1234567)) // 1,234,567
}
π€ Frequently Asked Questionsβ
Q1. How to ignore case?β
A: Use RegexOption!
fun main() {
val regex = Regex("hello", RegexOption.IGNORE_CASE)
println(regex.matches("Hello")) // true
println(regex.matches("HELLO")) // true
println(regex.matches("hello")) // true
}
Q2. How to escape characters?β
A: Use double backslash!
fun main() {
// Match . literally
val dotRegex = Regex("\\.")
println("3.14".contains(dotRegex)) // true
// Match ( ) literally
val parens = Regex("\\(.*\\)")
println("(test)".matches(parens)) // true
}
Q3. What about performance?β
A: Reuse compiled Regex!
// β Compile every time
fun bad(text: String): Boolean {
return text.matches(Regex("\\d+")) // slow
}
// β
Compile once
val NUMBER_REGEX = Regex("\\d+")
fun good(text: String): Boolean {
return text.matches(NUMBER_REGEX) // fast
}
π Pattern Referenceβ
Characters:
^ - start
$ - end
. - any character
\d - digit [0-9]
\D - not digit
\w - word character [a-zA-Z0-9_]
\W - not word character
\s - whitespace
\S - not whitespace
Quantifiers:
* - 0 or more
+ - 1 or more
? - 0 or 1
{n} - exactly n
{n,} - n or more
{n,m} - between n and m
Groups:
(...) - group
| - OR
[abc] - a, b, or c
[^abc] - not a, b, or c
[a-z] - a through z
π¬ Conclusionβ
Powerful string processing with regular expressions!
Key Takeaways:
β
Create patterns with Regex()
β
Full matching with matches()
β
Partial matching with find()
β
Replacement with replace()
β
Improve performance by reusing patterns
Next Step: Learn to create Kotlin-style APIs in DSL!