【问题标题】:Regex to replace html links to plain-text URLs正则表达式替换纯文本 URL 的 html 链接
【发布时间】:2010-02-25 01:30:20
【问题描述】:

我需要替换html中的链接:

<a href="http://example.com"></a>

到纯文本url地址:

http://example.com

UPD。这里有一些澄清,我需要这个来从文本中删除 html 标签,但保留链接位置。它纯粹供内部使用,因此不会有任何疯狂的边缘案例代码。 在这种情况下,语言是 python,但我不明白这有什么关系。

【问题讨论】:

  • 如果您需要操作 HTML,请不要使用正则表达式。
  • 您能确定作为参数输入的只是经过消毒的 还是会有其他位?
  • 太模棱两可了。什么语言,什么环境?
  • @zneak 真的吗?
  • @Conspicuous Compiler,公平地说,这不太可能发生(如果您对输入有一定程度的控制,或者愿意接受边缘情况下的不良结果,您可以做出一些妥协)。

标签: html regex


【解决方案1】:

正如我之前所说,如果您可以接受一些错误和/或对输入有一定程度的控制,您可以在完整性方面做出一些妥协并使用正则表达式。由于您的更新表明是这种情况,因此这里有一个适合您的正则表达式:

/<a\s(?:.(?!=href))*?href="([^"]*)"[^>]*?>(.*?)</a>/gi
  • $1:HREF
  • $2:标签内的所有内容。

这将处理下面的所有测试用例,除了最后三行:

Hello this is some text <a href="/test">This is a link</a> and this is some more text.
<a href="/test">Just a link on this line.</a>
There are <a href="/test">two links </a> on <a href="http://www.google.com">this line</a>!
Now we need to test some <a href="http://www.google.com" class="test">other attributes.</a>. They can be <a class="test" href="http://www.google.com">before</a> or after.
Or they can be <a rel="nofollow" href="http://www.google.com" class="myclass">both</a>
Also we need to deal with <a href="/test" class="myclass" style=""><span class="something">Nested tags and empty attributes</span></a>.
Make sure that we don't do anything with <a name="marker">anchors with no href</a>
Make sure we skip other <address href="/test">tags that start with a even if they are closed with an a</a>
Lastly try some other <a href="#">types</a> of <a href="">href</a> attributes.

Also we need to skip <a malformed tags.  </a>.  But <a href="#">this</a> is where regex fails us.
We will also fail if the user has used <a href='javascript:alert("the reason"))'>single quotes for some reason</a>
Other invalid HTML such as <a href="/link1" href="/link2">links with two hrefs</a> will have problems for obvious reasons.

【讨论】:

    【解决方案2】:
    >>> s="""blah <a href="http://example.com"></a> blah <a href="http://www.google.com">test</a>"""
    >>> import re
    >>> pat=re.compile("<a\s+href=\"(.*?)\">.*?</a>",re.M|re.DOTALL|re.I)
    >>> pat.findall(s)
    ['http://example.com', 'http://www.google.com']
    >>> pat.sub("\\1",s)
    'blah http://example.com blah http://www.google.com'
    

    对于更复杂的操作,使用 BeautifulSoup

    【讨论】:

    • 如果您的锚标签中有任何其他属性,这将不起作用......如果您尝试容纳它们,您的正则表达式将很快失控。
    【解决方案3】:

    您可以尝试将unlink 与minidom 一起使用,而不是使用正则表达式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 2015-03-12
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多