一、分割字符串
Kotlin正则使用和java完全相同
val test = "12.345-6.A"
val list = test.split("\\.|-".toRegex())//以'.'和'-'分割字符串
list.forEach { i -> println(i) }
val strs = test.split(".","-")//支持分隔字符作为参数,java不可以,因为'.'在正则中代表任何
strs.forEach { i -> println(i) }
二、正则表达式
"将解析文件的完整路径名称到对应的组件:目录、文件名和扩展名"的两种不同实现:
- 1.将使用扩展函数来处理字符串,
- 2.将使用正则表达式。
Kotlin标准库中包含了一些可以用来获取在给定分隔符第一次(或最后一次)出现之前(或之后)的子字符串的函数:
fun parsePath(path: String) {
val directory = path.substringBeforeLast("/")
val fullName = path.substringAfterLast("/")
val fileName = fullName.substringBeforeLast(".")
val extension = fullName.substringAfterLast(".")
println("directory is : $directory ,fullName is : $fullName, fileName : $fileName, extension : $extension")
}
fun main() {
parsePath("/Users/lynnlee/kotlin/readme.md")
}
打印结果
directory is : /Users/lynnlee/kotlin ,fullName is : readme.md, fileName : readme, extension : md
使用正则表达式也可以使用Kotlin标准库:
fun parsePathRegex(path: String) {
val regex = """(.+)/(.+)\.(.+)""".toRegex()
val matchResult = regex.matchEntire(path)
if (matchResult != null) {
val (directory, fileName, extension) = matchResult.destructured
println("directory : $directory ,fileName : $fileName, extension : $extension")
}
}
fun main() {
parsePathRegex("/Users/lynnlee/kotlin/readme.md")
}
打印结果
directory : /Users/lynnlee/kotlin ,fileName : readme, extension : md
正则表达式写在一个三重引号的字符串中。在这样的字符串中,不需要对任何字符进行转义,包括反斜线,所以可以使用.而不是\.来表示点,正如写一个普通的字符串的字面值一样。如果匹配成功,则将它的destructured属性赋值给相应的变量。这个和使用Pair初始化两个变量的语法是相同的。叫做解构声明。