regex - 如何使用正则表达式从字符串中提取第 n 个 URL?
问题描述
我想使用正则表达式提取第二个 URL,我不能使用任何其他东西,到目前为止,我已经设法使用正则表达式从字符串中提取所有 URL,但它只是给出了第一个 URL。
fun main() {
var text = "hello world https://www.google.com hello world https://www.stackoverflow.com hello world https://www.test.com"
var regex = """((http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)"""
println(performRegex(text, regex))
}
private fun performRegex(text: String?, regex: String?): String? {
val regexPattern = Regex("""$regex""")
return regexPattern.find(text.toString())?.value
}
解决方案
您可以使用
private fun performRegex(text: String?, regex: String?): String? {
val regexPattern = Regex("""$regex""")
val matchList = regexPattern.findAll(text.toString()).map{it.value}.toList()
return if (matchList.size >= 2) matchList[1] else null
}
fun main(args: Array<String>) {
var text = "hello world https://www.google.com hello world https://www.stackoverflow.com hello world https://w...content-available-to-author-only...t.com"
var regex = """(?:https?|ftp)://\S+"""
println(performRegex(text, regex))
}
请参阅在线 Kotlin 演示。
正则表达式是(?:https?|ftp)://\S+
, 它匹配http://
, https://
orftp://
然后是任何一个或多个非空白字符。
该val matchList = regexPattern.findAll(text.toString()).map{it.value}.toList()
部分查找所有匹配项并将结果映射到字符串列表。
如果匹配列表大小为两个或更多,则该return if (matchList.size >= 2) matchList[1] else null
部分返回找到的第二个匹配项,否则返回null
.
推荐阅读
- graphql - 使用 RDBMS 实现查询节点(id:ID!)的最佳方式是什么
- javascript - React 警告:在现有状态转换期间无法更新。搜索组件
- python - Python - Pandas - Style.ApplyMap 工作奇怪
- node.js - sequelize.import 不是函数
- maxima - 以最大值微分*函数*
- unreal-engine4 - PSVR可以连接虚幻引擎吗?
- java - 如何从我的 mac 中正确删除 java?
- html - 在 Razor 页面中将文本显示为 html
- xml - 在 XSD 文件中将 elementFormDefault="unqualified" 更改为 "qualified" 的影响
- c# - 在服务提供者上调用了“AddEntityFramework*”,但在 DbContext 选项配置中未调用“UseInternalServiceProvider”