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中的正则表达式可以用于执行许多字符串操作,包括匹配、提取、分割、替换和转义。