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]

相关方法

相关推荐
倾颜8 小时前
React 19 源码主线拆解 04:Fiber 到底是什么,React 为什么需要 Fiber?
前端·react.js·源码阅读
饭小猿人11 小时前
Android 腾讯X5WebView如何禁止系统自带剪切板和自定义剪切板视图
android·java
_李小白11 小时前
【android opencv学习笔记】Day 8: remap(像素位置重映射)
android·opencv·学习
美狐美颜SDK开放平台11 小时前
多场景美颜SDK解决方案:直播APP(iOS/安卓)开发接入详解
android·人工智能·ios·音视频·美颜sdk·第三方美颜sdk·短视频美颜sdk
嗷o嗷o12 小时前
Android BLE 里,MTU、分包和长数据发送到底该怎么处理
android
胡致和12 小时前
配置变更后,弹窗为什么飞到了最左边?
kotlin
Gary Studio14 小时前
Android AIDL HAL工程结构示例
android
y = xⁿ14 小时前
MySQL八股知识合集
android·mysql·adb
andr_gale15 小时前
04_rc文件语法规则
android·framework·aosp