【问题标题】:Remove all links with a specific protocol with RegEx使用 RegEx 删除具有特定协议的所有链接
【发布时间】:2022-01-21 16:46:31
【问题描述】:

我想从文本中删除所有链接,并将它们替换为以协议“example://”和“example_two://”开头的替代项。所有其他链接都应保持不变。

尽管我限制了链接类型,但以下正则表达式将替换所有链接:

(\<a).+?(example|example_two)?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))(.+?)</a>+"

有没有人建议更改正则表达式以按预期工作需要什么?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    根据链接中允许的字符,这应该有效:

    import re
    
    link1 = r'<a href=example_two://path.com/to/something?and_some_parameters=1234&and_ano%20ther_one=asdf />'
    link2 = r'<a> href="example_two://path.com/to/something?and_some_parameters=1234&and_another_one=asdf"</a>'
    
    pattern = re.compile(r"(?P<before>(?:(?P<opening><a>)|<a).*)(?:example|example_two)://[a-zA-Z0-9_/.=%?&$:;#,<>]*(?P<after>.*(?(opening)</a>|/>))")
    
    print(pattern.sub(r"\g<before>https://stackoverflow.com\g<after>", link1))
    print(pattern.sub(r"\g<before>https://example.com\g<after>", link2))
    
    # Prints:
    # <a href=https://stackoverflow.com/>
    # <a> href="https://example.com"</a>
    

    这会将链接之前的所有内容放入before 组中,将链接之后的所有内容放入after 组中,然后替换pattern.sub 中的完整匹配项。替换是 beforeafter 组中的匹配项的串联,替换链接在中间。

    更重要的是,结束标签以开始标签为条件。如果开始标签是&lt;a&gt;,则匹配的结束标签是&lt;/a&gt;,否则匹配/&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 2019-08-01
      相关资源
      最近更新 更多