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]

相关方法

相关推荐
Hy行者勇哥14 分钟前
物联网工控一体机操作系统选型:安卓、Ubuntu、Debian 场景化决策指南
android·物联网·ubuntu
llxxyy卢19 分钟前
polar网站被黑
android
阳光明媚sunny2 小时前
invalidate(),postInvalidate()和requestLayout()区别
android
用户41659673693552 小时前
兼容 Android Q+ 实现 WebView 图片长按保存与复制
android
2501_915918412 小时前
HTTP和HTTPS工作原理、安全漏洞及防护措施全面解析
android·http·ios·小程序·https·uni-app·iphone
Little丶Seven3 小时前
使用adb获取安卓模拟器日志
android·unity·adb·个人开发
凉栀お_3 小时前
MySQL第五次作业(触发器,存储过程)
android·mysql·adb
limingade3 小时前
ADB点击实战-做一个自动点广告播放领金币的脚本app(中)
android·adb·智能手机·ocr识别手机广告·ocr识别手机屏幕·adb自动关闭广告
珹洺3 小时前
Java-Spring入门指南(二十九)Android交互核心:按钮点击事件与Activity跳转实战
android·java·spring