【发布时间】:2017-04-25 00:11:31
【问题描述】:
我想用正则表达式从字符串中提取链接。我发现了一个类似的帖子here 并尝试了这段代码
let regex = try! NSRegularExpression(pattern: "<a[^>]+href=\"(.*?)\"[^>]*>.*?</a>")
let range = NSMakeRange(0, text.characters.count)
let htmlLessString :String = regex.stringByReplacingMatches(in: text,
options: [],
range:range ,
withTemplate: "")
但是建议的正则表达式删除了href标签的所有内容。我的字符串看起来像
SOME stirng <a href="https://com.mywebsite.com/yfgvh/f23/fsd" rel="DFGHJ"> some text I need to keep </a> and other text
预期的结果是
SOME stirng https://com.mywebsite.com/yfgvh/f23/fsd some text I need to keep and other text
完美的结果是
SOME stirng some text I need to keep (https://com.mywebsite.com/yfgvh/f23/fsd) and other text
您是否知道是否可以实现这一目标?
【问题讨论】:
-
当你使用分组时(因为我认为你想保留字符串)。你为什么不使用 nstextcheckingresult - developer.apple.com/reference/foundation/nstextcheckingresult 现在循环你的匹配 stackoverflow.com/questions/13707187/… 正如你在这里看到的那样,只替换后缀 "\"[^>] 处的前缀 "]+href=\"" *>.*?"" ?
-
这是
NSDataDetector的内置功能。您是否尝试过使用它而不是构建自己的正则表达式?