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]

相关方法

相关推荐
天花板之恋23 分钟前
MutableStateFlow、StateFlow、LiveData在Compose中的运用
kotlin·workflow
我命由我123451 小时前
Android PDF 操作 - AndroidPdfViewer 显示 PDF 异常清单(数据为 null、数据为空、PDF 文件损坏、非 PDF 文件)
android·java·java-ee·pdf·android studio·android-studio·android runtime
zhilin_tang1 小时前
揭开Linux跨平台 adb调试原理神秘面纱
android·linux
撩得Android一次心动2 小时前
Android 四大组件——Activity
android
TimeFine3 小时前
Android 网络请求超时?可能与连接池和脏连接有关
android
Digitally4 小时前
如何将安卓手机备份到电脑?7种方法
android
火柴就是我5 小时前
android:enableJetifier=true 再学习
android·flutter
杨筱毅5 小时前
【Android】【底层原理】深入解析SELinux模块
android·底层机制
Tom4i6 小时前
基于 Launcher3 的 iOS 风格桌面 04 拖拽和移位
android
2501_915106326 小时前
iOS 反编译防护工具与实战组合 从静态侦察到 IPA 成品加固的工程化路径
android·ios·小程序·https·uni-app·iphone·webview