You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin如何将同时包含数字与字符的字符串拆分为多段子串

Kotlin 拆分混合数字与非数字字符串方案

需求说明

需要将同时包含数字、普通字符的长字符串,按「连续数字块」「连续非数字块」拆分,保留原始所有空格、符号。示例如下:

输入:Buy these 2 products and get 100 off
期望输出:["Buy these ","2 ","products and get ","100 ","off"]

实现方案

使用正则匹配实现,逻辑简洁且性能满足普通业务场景:

  • 匹配规则用正则表达式\d+|\D+:\d+匹配1个及以上连续数字,\D+匹配1个及以上连续非数字,按字符串顺序逐个捕获所有符合规则的片段,不会丢失原始字符。
  • Kotlin 中调用Regex类的findAll方法即可完成所有片段的提取。

完整代码示例

fun splitMixedString(input: String): List<String> {
    // 正则匹配连续数字段或连续非数字段
    val mixedRegex = Regex("\\d+|\\D+")
    return mixedRegex.findAll(input)
        .map { matchedResult -> matchedResult.value }
        .toList()
}

// 测试用例
fun main() {
    val testInput = "Buy these 2 products and get 100 off"
    val splitResult = splitMixedString(testInput)
    println(splitResult)
    // 运行输出:[Buy these , 2 , products and get , 100 , off],完全匹配预期
}

可选调整

如果不需要保留片段前后的空格,可在map阶段调用trim()方法修改为.map { it.value.trim() }即可。


内容的提问来源于stack exchange,提问作者Bincy Baby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:03:01