我想从正则表达式中提取字符串中的链接。我发现了一个类似的帖子here我试过这个代码正则表达式来提取href url
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 - https://developer.apple.com/reference/foundation/nstextcheckingresult现在通过你的匹配循环http://stackoverflow.com/questions/13707187/regex-to-extract-all-the-substrings在两个字符之间或标签之间,你可以在这里看到,并且只在后缀“\”[^>] *>。*?处替换前缀“] + href = \”“? – Lepidopteron
使用'NSDataDetector'实现内置功能您是否尝试过使用该函数而不是构建自己的正则表达式? –