正则expression式在ios中提取href url并丢弃锚标签的其余部分?

我想在目标C中编写一个URL提取函数。input文本可以是任何东西,可能包含也可能不包含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>"; 

我想修改string为"This is cool site https://abc.com/coolstuff

忽略锚标记之间的所有文本。 而且需要考虑其他属性,如锚点标记中的_target

我可以做类似的事情

 static NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<a\shref=\"(.*?)\">.*?</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="([^"]+) 

EXPLAINED

<a – 匹配开始标记

.+? – 任何事情懒洋洋地匹配

href=" – 匹配href属性

([^"]+) – 捕获href值

OUTPUT

 https://abc.com/coolstuff https://abc.com/coolstuff https://abc.com/coolstuff