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]

相关方法

相关推荐
plainGeekDev2 小时前
文件读写(Java IO)→ Kotlin 扩展函数
android·java·kotlin
s_nshine2 小时前
释放C盘,迁移studio相关数据到其他盘
android·windows·android studio·内存·c盘
韩曙亮3 小时前
【Flutter】Flutter 中的 Android / iOS 特殊配置 ① ( 网络权限配置 | HTTP 明文传输配置 | 应用名称配置 )
android·网络·flutter·http·ios·网络权限
_李小白3 小时前
【android opencv学习笔记】Day 31:提取轮廓之Canny算法
android·opencv·学习
hashiqimiya4 小时前
每日android布局xml文件
android·xml·gitee
m0_738120724 小时前
渗透测试基础——PHP 序列化数据结构与反序列化机制详解
android·服务器·网络·数据结构·安全·php
故渊at5 小时前
第二板块:Android 四大组件标准化学理 | 第十一篇:组件间通信(IPC)与 Binder 深度解析
android·binder·组件化·组件间通信
ZC跨境爬虫5 小时前
跟着 MDN 学JavaScript day_10:数组——数据的有序集合
android·java·开发语言·前端·javascript
消失的旧时光-19435 小时前
Kotlin 协程设计思想(九):Flow 到底是什么?为什么 suspend 函数还需要 Flow?
android·kotlin·协程·协程异常