java - 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
我的意思是如何匹配字符串中的第一个或第二个或倒数第三个数字。
解决方案
您可以使用捕获组来解决这个问题
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())
}
}
推荐阅读
- arduino - BLE 连接超时?
- c# - 无法在 xUnit 中捕获 InvalidOperationException
- i18next - 将过滤器应用于嵌套组件
- json - Dart/Flutter 中用于 FHIR 资源的 Json oneOf
- javascript - Firestore/Javascript:如何从子文档的地图字段中获取数据?
- templates - ServiceStack:运行“web new web-corefx ProjectName”创建一个 .NET Framework 4.x 项目
- c# - WPF:过滤 ComboBox 的 ItemCollection 还会过滤绑定到同一 ItemsSource 的其他 ComboBox
- php - 如何在没有第二次选择的情况下对平均函数结果应用 where 条件?
- java - JavaFX:Stage show() 方法的问题
- parsing - 为什么 soup.find_all 总是返回一个空字符串,即使在指定的类中存在非常清楚的标签?