1 回答
TA贡献2011条经验 获得超2个赞
您可以使用以下正则表达式来实现:["']+[^"']+?["']+. 使用该模式,您可以检索要拆分的索引,如下所示:
val indices = Regex(pattern).findAll(this).map{ listOf(it.range.start, it.range.endInclusive) }.flatten().toMutableList()
剩下的就是用子字符串构建列表。这里完整的功能:
fun String.splitByPattern(pattern: String): List<String> {
val indices = Regex(pattern).findAll(this).map{ listOf(it.range.start, it.range.endInclusive) }.flatten().toMutableList()
var lastIndex = 0
return indices.mapIndexed { i, ele ->
val end = if(i % 2 == 0) ele else ele + 1 // magic
substring(lastIndex, end).apply {
lastIndex = end
}
}
}
用法:
val str = """
this "'"is a possible option"'" and ""so is this"" and '''this one too''' and even ""mismatched quotes"
""".trim()
println(str.splitByPattern("""["']+[^"']+?["']+"""))
输出:
[this , "'" is a possible option"'", and , ""so is this"", and , '''this one too''', and even , ""mismatched quotes"]
在Kotlin 的操场上试试吧!
添加回答
举报
