【问题标题】:Regex to replace url with a word python正则表达式用一个单词 python 替换 url
【发布时间】:2021-05-13 20:32:43
【问题描述】:

我正在尝试替换长字符串中的几个 url。

这里是一个示例:

s = 'https://www.yellowpages.ca/bus/Alberta/Edmonton/MNS-Enterprise-\nLtd/8114324.html, https://411.ca/business/profile/13300641'

由于 url 中的换行符,匹配将始终在 \n 处停止。 我试过了

re.sub(r'(https?://[\S]*)', 'website__', s, re.DOTALL)

但结果在\n 中断

'website__\nLtd/8114324.html, website__'

【问题讨论】:

    标签: python regex url


    【解决方案1】:

    您可以添加\n并使用

    re.sub(r'https?://[\n\S]+\b', '<URL>', s)
    

    请参阅regex demo详情

    • https?:// - http://https://
    • [\n\S]+ - 一个或多个换行符或非空白字符
    • \b - 直到最右边的单词边界。

    Python demo

    import re
    s = 'https://www.yellowpages.ca/bus/Alberta/Edmonton/MNS-Enterprise-\nLtd/8114324.html, https://411.ca/business/profile/13300641'
    print( re.sub(r'https?://[\n\S]+\b', 'website__', s) )
    # => website__, website__
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2023-03-10
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2016-06-26
      相关资源
      最近更新 更多