【问题标题】:Regular expression in ios to extract href url and discard rest of anchor tag?ios中的正则表达式提取href url并丢弃其余的锚标记?
【发布时间】:2014-03-12 21:35:19
【问题描述】:

我想在Objective 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:@"<a\shref=\"(.*?)\">.*?</a>" options:NSRegularExpressionCaseInsensitive error:nil];;
NSString* modifiedString = [regex stringByReplacingMatchesInString:inputString options:0 range:NSMakeRange(0, [inputString length]) withTemplate:@"$1"];

使用 input1 可以正常工作,但在其他情况下会失败。

谢谢

【问题讨论】:

标签: html ios regex nsregularexpression


【解决方案1】:

试试这个:

<a[^>]+href=\"(.*?)\"[^>]*>.*?</a>

【讨论】:

  • ]+href[ ]*=[ ]*\"(.*?)\"[^>]*>(.*?) 更好.也许“href”和“=”之间有空格。
  • 如何使用它使纯文本像链接一样可点击,所以点击纯文本时会打开 href 链接?
【解决方案2】:

或者试试这个:

<a.+?href="([^"]+)

解释

&lt;a - 匹配开始标签

.+? - 懒惰地匹配任何东西

href=" - 匹配 href 属性

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

输出

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

【讨论】:

    【解决方案3】:
    <[aA].+href[ ]*=[ ]*[\\]?"(.*)[\\]".*>(.+)<\/[aA]>
    

    在这里,第一组 ($1) 捕获 url。 $2 捕获链接文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      相关资源
      最近更新 更多