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]

相关方法

相关推荐
索迪迈科技33 分钟前
影视APP源码 SK影视 安卓+苹果双端APP 反编译详细视频教程+源码
android·影视app源码·sk影视
孔丘闻言41 分钟前
python调用mysql
android·python·mysql
萧雾宇3 小时前
Android Compose打造仿现实逼真的烟花特效
android·flutter·kotlin
翻滚丷大头鱼3 小时前
android 性能优化—ANR
android·性能优化
翻滚丷大头鱼3 小时前
android 性能优化—内存泄漏,内存溢出OOM
android·性能优化
拜无忧4 小时前
【教程】flutter常用知识点总结-针对小白
android·flutter·android studio
拜无忧5 小时前
【教程】Flutter 高性能项目架构创建指南:从入门到高性能架构
android·flutter·android studio
用户2018792831675 小时前
故事:公司的 "私人储物柜" 系统(ThreadLocalMap)
android·java
CYRUS_STUDIO5 小时前
如何防止 so 文件被轻松逆向?精准控制符号导出 + JNI 动态注册
android·c++·安全
yinmaisoft5 小时前
当低代码遇上AI,有趣,实在有趣
android·人工智能·低代码·开发工具·rxjava