You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何编写正则匹配提取含双/单引号及无引号的href链接

你需要的正则表达式可以同时匹配无引号、双引号、单引号包裹的href属性,同时提取链接地址和标签文本,模式如下:

<a href=(["']?)([^"'>]+)\1>([^<]+)</a>

正则模式解释

  • (["']?):捕获可选的单引号或双引号(如果存在),后续用\1反向引用,保证前后引号一致
  • ([^"'>]+):捕获href的链接内容,排除引号和<,避免匹配超出href范围的内容
  • \1:反向引用前面捕获的引号(如果有),确保引号闭合
  • ([^<]+):捕获标签内的文本内容,直到遇到<结束标签为止

Swift代码实现示例

import Foundation

let htmlContent = """
A regex to match href and extract info <a href=https://www.google.com>Google</a>.
<a href="https://www.google.com">Google</a> 
<a href='https://www.google.com'>Google</a>
"""

// 使用Raw String避免转义字符的繁琐处理
let pattern = #"<a href=(["']?)([^"'>]+)\1>([^<]+)</a>"#

do {
    // 添加.caseInsensitive选项支持匹配<A>这类大写标签
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let matches = regex.matches(in: htmlContent, range: NSRange(htmlContent.startIndex..., in: htmlContent))
    
    for match in matches {
        // 提取分组2的链接内容
        guard let linkRange = Range(match.range(at: 2), in: htmlContent) else { continue }
        let link = String(htmlContent[linkRange])
        
        // 提取分组3的标签文本
        guard let textRange = Range(match.range(at: 3), in: htmlContent) else { continue }
        let text = String(htmlContent[textRange])
        
        print("链接地址: \(link)")
        print("显示文本: \(text)\n")
    }
} catch {
    print("正则初始化错误: \(error.localizedDescription)")
}

运行结果

链接地址: https://www.google.com
显示文本: Google

链接地址: https://www.google.com
显示文本: Google

链接地址: https://www.google.com
显示文本: Google

注意事项

这个正则仅适用于你描述的简单场景:

内容的提问来源于stack exchange,提问作者FarouK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:05:48