跳至正文

🔍 正規表達式

📖 什麼是正規表達式?

**正規表達式(Regular Expression, Regex)**是一種表達字串模式的方法。用於搜尋、驗證、提取、替換等操作!

💡 基本用法

建立 Regex

fun main() {
// 建立 Regex 物件
val regex1 = Regex("hello")
val regex2 = "hello".toRegex()

// 確認匹配
println(regex1.matches("hello")) // true
println(regex1.matches("Hello")) // false (區分大小寫)
}

簡單匹配

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
}

🎯 基本模式

字元類別

fun main() {
// \d - 數字
println("123".matches(Regex("\\d+"))) // true

// \w - 文字(英文、數字、_)
println("hello_123".matches(Regex("\\w+"))) // true

// \s - 空白
println(" ".matches(Regex("\\s"))) // true

// . - 任意字元
println("abc".matches(Regex("..."))) // true (3個字元)
}

量詞

fun main() {
// + : 1個以上
println("aaa".matches(Regex("a+"))) // true

// * : 0個以上
println("".matches(Regex("a*"))) // true

// ? : 0個或1個
println("a".matches(Regex("a?"))) // true

// {n} : 正好n個
println("aaa".matches(Regex("a{3}"))) // true

// {n,m} : n個以上m個以下
println("aaa".matches(Regex("a{2,4}"))) // true
}

🎨 實戰範例

電子郵件驗證

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
}

電話號碼驗證

fun isValidPhone(phone: String): Boolean {
// 010-1234-5678 或 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
}

密碼強度

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 -> "非常強"
hasLength && hasDigit && (hasLower || hasUpper) -> "強"
hasLength -> "普通"
else -> "弱"
}
}

fun main() {
println(checkPasswordStrength("Pass123!")) // 非常強
println(checkPasswordStrength("password123")) // 強
println(checkPasswordStrength("password")) // 普通
println(checkPasswordStrength("pass")) // 弱
}

URL 提取

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
}

標籤提取

fun extractHashtags(text: String): List<String> {
val pattern = "#\\w+"
return Regex(pattern).findAll(text).map { it.value }.toList()
}

fun main() {
val tweet = "오늘 날씨 좋네요 #날씨 #행복 #코틀린"
val hashtags = extractHashtags(tweet)

println("標籤:")
hashtags.forEach { println(it) }
// #날씨
// #행복
// #코틀린
}

🔧 進階功能

群組捕獲

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")
}
}

替換

fun main() {
val text = "My phone is 010-1234-5678"

// 電話號碼遮罩
val masked = text.replace(Regex("\\d{4}$"), "****")
println(masked) // My phone is 010-1234-****

// 將多個空白變成一個
val multiSpace = "Hello World !"
val cleaned = multiSpace.replace(Regex("\\s+"), " ")
println(cleaned) // Hello World !
}

分割

fun main() {
// 用逗號或空白分割
val text = "apple, banana orange,grape"
val fruits = text.split(Regex("[,\\s]+"))
println(fruits) // [apple, banana, orange, grape]

// 用數字分割
val text2 = "item1,item2,item3"
val items = text2.split(Regex("\\d+"))
println(items) // [item, ,item, ,item, ]
}

🎯 實用模式

移除 HTML 標籤

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!
}

提取數字

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]
}

金額格式化

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
}

🤔 常見問題

Q1. 如何忽略大小寫?

A: 使用 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. 如何跳脫字元?

A: 使用兩個反斜線!

fun main() {
// 將 . 當作字元本身匹配
val dotRegex = Regex("\\.")
println("3.14".contains(dotRegex)) // true

// 將 ( ) 當作字元本身
val parens = Regex("\\(.*\\)")
println("(test)".matches(parens)) // true
}

Q3. 效能如何?

A: 重複使用編譯好的 Regex!

// ❌ 每次都編譯
fun bad(text: String): Boolean {
return text.matches(Regex("\\d+")) // 慢
}

// ✅ 只編譯一次
val NUMBER_REGEX = Regex("\\d+")
fun good(text: String): Boolean {
return text.matches(NUMBER_REGEX) // 快
}

📚 主要模式整理

字元:
^ - 開頭
$ - 結尾
. - 任意字元
\d - 數字 [0-9]
\D - 非數字
\w - 文字 [a-zA-Z0-9_]
\W - 非文字
\s - 空白
\S - 非空白

數量:
* - 0個以上
+ - 1個以上
? - 0個或1個
{n} - 正好n個
{n,} - n個以上
{n,m} - n個以上m個以下

群組:
(...) - 群組
| - OR
[abc] - a、b、c 其中之一
[^abc] - 不是 a、b、c
[a-z] - 從 a 到 z

🎬 結語

用正規表達式進行強大的字串處理!

重點整理:
✅ 用 Regex() 建立模式
✅ 用 matches() 進行完整匹配
✅ 用 find() 進行部分匹配
✅ 用 replace() 進行替換
✅ 重複使用模式提升效能

下一步:在 DSL 中建立 Kotlin 風格的 API!