Regex将url替换为单词python

2024-09-24 22:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试替换长字符串中的几个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__'

Tags: 字符串httpsreurlhtmlwwwwebsite例子
1条回答
网友
1楼 · 发布于 2024-09-24 22:28:35

您可以添加\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__

相关问题 更多 >