首页 > 解决方案 > kotlin/java 用正则表达式匹配字符串中的数字

问题描述

例如,如果我有这些字符串,有什么方法可以得到所有这些字符串中的 123 个,或者 777 或 888 个?

https://www.example.com/any/123/

https://www.example.com/any/777/123/

https://www.example.com/any/777/123/888

我的意思是如何匹配字符串中的第一个或第二个或倒数第三个数字。

标签: javaregexkotlin

解决方案


您可以使用捕获组来解决这个问题

val strList = listOf("https://www.example.com/any/777/123/888", "https://www.example.com/any/123/", "https://www.example.com/any/777/123/")
val intList = mutableListOf<Int>()
val regex = Regex("/?(\\d+)")

strList.forEach { str ->
    regex.findAll(str).forEach {
        intList.add(it.groupValues[1].toInt())
    }
}

推荐阅读