Swift中如何编写正则匹配提取含双/单引号及无引号的href链接
在Swift中匹配HTML 标签三种格式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
相关产品推荐
相关产品推荐

