Kam*_*ran 5 html regex ios nsregularexpression
我想在目标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>";
Run Code Online (Sandbox Code Playgroud)
我想修改字符串为 "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"];
Run Code Online (Sandbox Code Playgroud)
使用input1工作正常但在其他情况下失败.
谢谢
或尝试以下方法:
<a.+?href="([^"]+)
Run Code Online (Sandbox Code Playgroud)
<a -匹配开始标签
.+? -懒惰地匹配任何东西
href=" -匹配href属性
([^"]+) -获取href值
https://abc.com/coolstuff
https://abc.com/coolstuff
https://abc.com/coolstuff
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5217 次 |
| 最近记录: |