Kotlin MatchResult.Destructured用法及代码示例

本文方法及代码示例基于Kotlin 2.1.20 Released

MatchResult.Destructured 所在包 kotlin.text.MatchResult.Destructured,其相关用法介绍如下。

用法:

kotlin 复制代码
class Destructured

提供用于解构组值分配的组件。

component1 对应于第一组的值,component2 --- 第二组的值,依此类推。

如果正则表达式中的组是可选的,并且该组没有捕获到匹配项,则相应的组件值为空字符串。

示例代码:

kotlin 复制代码
fun main(args: Array<String>) {
    //sampleStart
    val inputString = "John 9731879"
    val match = Regex("(\w+) (\d+)").find(inputString)!!
    val (name, phone) = match.destructured

    println(name) // John     // value of the first group matched by \w+
    println(phone) // 9731879 // value of the second group matched by \d+

    // group with the zero index is the whole substring matched by the regular expression
    println(match.groupValues) // [John 9731879, John, 9731879]

    val numberedGroupValues = match.destructured.toList()
    // destructured group values only contain values of the groups, excluding the zeroth group.
    println(numberedGroupValues) // [John, 9731879]
    //sampleEnd
}

// 输出
John
9731879
[John 9731879, John, 9731879]
[John, 9731879]

相关方法

相关推荐
曾经我也有梦想1 小时前
Day4 Kotlin 高级特性
android
simplepeng1 小时前
Compose Multiplatform 中的 Navigation 3
android
Kapaseker7 小时前
一杯美式讲完 Sealed Class
android·kotlin
冬奇Lab18 小时前
PowerManagerService(下):Doze模式与电池优化
android·源码阅读
砖厂小工20 小时前
Compose 中函数引用 vs Lambda:到底该用哪个?
android
Kapaseker1 天前
详解 Compose background 的重组陷阱
android·kotlin
黄林晴1 天前
Kotlin 2.3.20-RC2 来了!JPA 开发者狂喜,6 大更新一文速览
android·kotlin
冬奇Lab2 天前
OpenClaw 深度解析(八):Skill 系统——让 LLM 按需学习工作流
人工智能·开源·源码阅读
kymjs张涛2 天前
OpenClaw 学习小组:初识
android·linux·人工智能
糖猫猫cc2 天前
Kite:填充处理器
kotlin·orm·kite