如何使用正则表达式从字符串中提取第n个URL?
调整方案
核心原因:原有代码使用的find()方法仅返回第一个匹配结果,若要获取指定序号的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@?^=%&\/~+#-])?)""" // 第二个URL对应索引为1(索引从0开始计数) println(performRegex(text, regex, 1)) } private fun performRegex(text: String?, regex: String?, targetIndex: Int): String? { // 提前做异常场景校验 if (text.isNullOrEmpty() || regex.isNullOrEmpty() || targetIndex < 0) return null val regexPattern = Regex(regex) // 获取所有匹配结果 val matchList = regexPattern.findAll(text).toList() // 校验索引不越界后返回对应值 return if (targetIndex < matchList.size) matchList[targetIndex].value else null }
逻辑说明
- 调用
Regex.findAll()方法替代原有find()方法,该方法会返回所有匹配结果的序列,转为列表后即可按索引访问 - 序号从0开始计数,第一个URL对应索引0,第二个对应索引1,以此类推
- 新增了空值、索引越界校验,避免运行时异常
内容的提问来源于stack exchange,提问作者Vaibhav Chopade
相关产品推荐
相关产品推荐

