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]

相关方法

相关推荐
用户74589002079541 小时前
线程池
android
专注前端30年1 小时前
【PHP开发与安全防护实战】性能调优手册
android·安全·php
王正南3 小时前
安卓逆向之LSposed开发(一)
android·xposed·lsposed
YIN_尹3 小时前
【MySQL】数据类型(上)
android·mysql·adb
zh_xuan4 小时前
kotlin 类继承的语法
开发语言·kotlin
robotx5 小时前
AOSP设备节点权限添加相关
android
顾林海5 小时前
Android文件系统安全与权限控制:给应用数据上把“安全锁”
android·面试·操作系统
青莲8435 小时前
Android 动画机制完整详解
android·前端·面试
城东米粉儿5 小时前
android 离屏预渲染 笔记
android
未知名Android用户5 小时前
Android自定义 View + Canvas—声纹小球动画
android