我想在目标C中编写一个url提取函数。输入文本可以是任何内容,可能包含也可能不包含 html 锚标记。
考虑一下:
NSString* input1 = @"This is cool site <a href="https://abc.com/coolstuff"> Have fun exploring </a>";
NSString* input2 = @"This is cool site <a target="_blank" href="https://abc.com/coolstuff"> Must visit </a>";
NSString* input3 = @"This is cool site <a href="https://abc.com/coolstuff" target="_blank" > Try now </a>";
我希望修改后的字符串"This is cool site https://abc.com/coolstuff
忽略锚标记之间的所有文本。并且需要考虑其他属性,例如锚标记中的_target
我可以做类似的事情
static NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<ashref="(.*?)">.*?</a>" options:NSRegularExpressionCaseInsensitive error:nil];;
NSString* modifiedString = [regex stringByReplacingMatchesInString:inputString options:0 range:NSMakeRange(0, [inputString length]) withTemplate:@"$1"];
使用 input1 工作正常,但在其他情况下失败。
谢谢
试试这个:
<a[^>]+href="(.*?)"[^>]*>.*?</a>
或者试试这个:
<a.+?href="([^"]+)
解释
<a
- 匹配开始标记
.+?
- 懒惰地匹配任何内容
href="
- 匹配 href 属性
([^"]+)
- 捕获 href 值
输出
https://abc.com/coolstuff
https://abc.com/coolstuff
https://abc.com/coolstuff
<[aA].+href[ ]*=[ ]*[\]?"(.*)[\]".*>(.+)</[aA]>
在这里,第一组($1)捕获URL,$2捕获链接文本。