Kotlin中的正則表達式(Regular Expressions)是一種用于處理字符串的強大工具。它可以用于以下操作:
val emailPattern = Regex("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b")
val email = "example@example.com"
println(emailPattern.matches(email)) // 輸出: true
val text = "Please contact us at support@example.com or call us at 123-456-7890."
val emailPattern = Regex("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b")
val emails = text.findAll(emailPattern)
println(emails) // 輸出: [support@example.com]
val input = "apple,banana,orange,grape"
val pattern = Regex(",")
val fruits = input.split(pattern)
println(fruits) // 輸出: [apple, banana, orange, grape]
val input = "I have 3 cats and 5 dogs."
val numberPattern = Regex("\\d+")
val output = input.replace(numberPattern) { it.value.toString().capitalize() }
println(output) // 輸出: I have Three cats and Five dogs.
.
、*
、?
等。你可以使用\\
字符對這些特殊字符進行轉義,使其在正則表達式中具有普通字符的含義。val input = "The price is $100."
val pattern = Regex("\\$(\\d+)")
val match = pattern.find(input)
println(match?.groupValues) // 輸出: [100]
總之,Kotlin中的正則表達式可以用于執行許多字符串操作,包括匹配、提取、分割、替換和轉義。