【问题标题】:I need a regex to find a url which is not inside any html tag or an attribute value of any html tag我需要一个正则表达式来查找不在任何 html 标记或任何 html 标记的属性值内的 url
【发布时间】:2013-06-06 22:55:30
【问题描述】:

我在以下文本中有 html 内容。

    "This is my text to be parsed which contains url 
    http://someurl.com?param1=foo&params2=bar 
 <a href="http://thisshouldnotbetampered.com">
    some text and a url http://someotherurl.com test 1q2w
 </a> <img src="http://someasseturl.com/abc.jpeg"/>
    <span>i have a link too http://someurlinsidespan.com?xyz=abc </span> 
    "

需要一个将普通网址转换为超链接的正则表达式(不篡改现有的超链接)

预期结果:

    "This is my text to be parsed which contains url 
    <a href="http://someurl.com?param1=foo&params2=bar">
http://someurl.com?param1=foo&params2=bar</a> 
 <a href="http://thisshouldnotbetampered.com">
    some text and a url http://someotherurl.com test 
1q2w </a> <img src="http://someasseturl.com/abc.jpeg"/>
    <span>i have a link too <a href="http://someurlinsidespan.com?xyz=abc">http://someurlinsidespan.com?xyz=abc</a> </span> "

【问题讨论】:

  • 正则表达式可能不是这项工作的正确工具。考虑替代方案:nokogiri.org
  • 我不知道 Ruby 的正则表达式实现,但在 www.regex101.com 中可以正常工作。只要您知道可能输入的结构,正则表达式就可以了。

标签: ruby regex ruby-on-rails-3 rubular


【解决方案1】:

免责声明:您不应使用正则表达式来完成此任务,而应使用 html 解析器。这是一个POC,以证明如果您期望一个格式良好的 HTML(无论如何您都不会拥有),这是可能的。

这就是我想出的:
(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)(?![^&lt;]*?(?:&lt;\/\w+&gt;|\/?&gt;))

这是什么意思?

  • (:第一组
  • https? :匹配 httphttps
  • \/\/ :匹配 //
  • (?:w{1,3}.)? :可选匹配 w.ww.www.
  • [^\s]*? :匹配除空格以外的任何内容零次或多次不贪婪
  • (?:\.[a-z]+)+) :匹配一个点后跟 [a-z] 字符,重复一次或多次
  • (?!:负前瞻
    • [^&lt;]*? :匹配除 &lt; 之外的任何内容零次或多次不贪婪
    • (?:&lt;\/\w+&gt;|\/?&gt;) :匹配结束标签或 /&gt;&gt;
    • ) : 前瞻结束
  • ) : 第 1 组结束


regex101 online demo rubular online demo

【讨论】:

  • 好的。我的错。答案有效,但不适用于真实场景所以让我直截了当地说。我想让文本中的所有 url 成为超链接。 (正则表达式不应篡改现有的超链接)。上面的正则表达式也没有捕获 url 参数。
  • @krunalshah 我倾向于为现有问题提供答案。你没有提到任何你想匹配 url 参数的地方,甚至在你的例子中也没有。那么在您的实际场景中什么不起作用?
【解决方案2】:

也许您可以先进行搜索和替换以删除 HTML 元素。我不了解 Ruby,但正则表达式类似于 /&lt;(\w+).*?&gt;.*?&lt;/\1&gt;/。但是,如果您有相同类型的嵌套元素,这可能会很棘手。

【讨论】:

  • +1 用于删除标签,但如果您想使用正则表达式,该表达式可能会更好。例如,它不会删除图像标签,或者会删除整个段落 (&lt;p&gt;i want http://this.url&lt;/p&gt;)。我建议像&lt;/?\w+[^&gt;]*&gt; 这样简单的东西。
  • 我不同意你对这个问题的解释,但这是一个有争议的问题,因为问题现在已经改变了。
【解决方案3】:

也许尝试http://rubular.com/ .. 有一些Regex 提示可以帮助您获得所需的输出。

【讨论】:

    【解决方案4】:

    我会这样做:

    require 'nokogiri'
    
    doc = Nokogiri::HTML.fragment <<EOF
    This is my text to be parsed which contains url 
    http://someurl.com  <a href="http://thisshouldnotbetampered.com">
    some text and a url http://someotherurl.com test 1q2w </a> <img src="http://someasseturl.com/abc.jpeg"/>
    EOF
    
    doc.search('*').each{|n| n.replace "\n"}
    
    URI.extract doc.text
    #=> ["http://someurl.com"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 2010-11-24
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多