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]

相关方法

相关推荐
余额瞒着我当琳2 小时前
C++模板初阶与STL初探
android·java·c++
知行合一。。。5 小时前
DeepAgents--01--Agent和OpenClaw的相关概念
android·数据库
汪海游龙6 小时前
告别 Play Console 手动上传:从模拟器截图到自动发版的完整流水线
android·ci/cd·github
weixin_440784116 小时前
【IntentSeivice实现原理】
android·java·开发语言·intentservice
delta_hell6 小时前
【阅读源码--Android】动画之ValueAnimator--2
android·源码·valueanimator
delta_hell6 小时前
【阅读源码--Android】动画之辅助类
android·源码·animator
学习使我健康7 小时前
一个基于 **Jetpack Compose + Material 3** 的 Android 入门示例项目,演示 Compose 声明式 UI 的核心用法
ui·kotlin·android jetpack
delta_hell10 小时前
【阅读源码--Android】动画之ValueAnimator--1
android·源码·valueanimator
消失的旧时光-194310 小时前
第 2 篇:Android 控制屏为什么与机器人主控使用 TCP 长连接?
android·tcp/ip·机器人
小Ti客栈11 小时前
MySQL查询原理:从Server到InnoDB
android·mysql·adb