首页 > 解决方案 > 如何使用正则表达式从字符串中提取第 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
}

当前输出:https ://www.google.com

预期输出:https ://www.stackoverflow.com

标签: regexkotlin

解决方案


您可以使用

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.


推荐阅读