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]

相关方法

相关推荐
提子拌饭1332 小时前
番茄时间管理:鸿蒙Flutter 实现的高效时间管理工具
android·flutter·华为·架构·开源·harmonyos·鸿蒙
4311媒体网2 小时前
帝国CMS二次开发实战:精准实现“最新资讯”标识与高亮判断
android
BLUcoding2 小时前
Android 轻量级本地存储 SharedPreferences
android
冬奇Lab2 小时前
Camera HAL3 接口:Android 相机的真正底牌
android·音视频开发·源码阅读
sensen_kiss3 小时前
CAN302 Technologies for E-Commerce 电子商务技术 Pt.6 市场营销与SEO(搜索引擎优化)
android·学习·搜索引擎
UXbot3 小时前
2026年AI全链路产品开发工具对比:5款从创意到上线一站式平台深度解析
前端·ui·kotlin·软件构建·swift·原型模式
菜鸟国国3 小时前
Compose + Koin ViewModel 实战完全手册
android
小羊子说3 小时前
Android 音频系统深度解析:从 App 到内核的完整链路
android·人工智能·性能优化·车载系统
fengci.3 小时前
php反序列化(复习)(第三章)
android·开发语言·学习·php
D4c-lovetrain3 小时前
linux个人心得24 (mysql③,AI排版尝试)
android·adb