正则表达式在ios中提取href url并丢弃锚标签的其余部分? [英] Regular expression in ios to extract href url and discard rest of anchor tag?
本文介绍了正则表达式在ios中提取href url并丢弃锚标签的其余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在目标C中编写一个url提取函数。输入文本可以是任何内容,可以包含也可以不包含html定位标记。
请考虑这一点:
NSString * input1 = @This is cool site< a href =https://abc.com/coolstuff> ;尽情探索< / a>;
NSString * input2 = @This is cool site< a target =_ blankhref =https://abc.com/coolstuff>必须访问< / a>;
NSString * input3 = @This is cool site< a href =https://abc.com/coolstufftarget =_ blank>立即试用< / a>;
我想修改字符串为这是很棒的网站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>
I want to write a url extracting function in objective C. The input text can be anything and may or may not contain html anchor tags.
Consider this:
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>";
I want modified string as "This is cool site https://abc.com/coolstuff
Ignoring all text between anchor tag. And need to consider other attributes like _target in anchor tag
I can do something like
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"];
Works fine with input1 but fails in other cases.
Thanks
解决方案
Try this one:
<a[^>]+href=\"(.*?)\"[^>]*>.*?</a>
这篇关于正则表达式在ios中提取href url并丢弃锚标签的其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文