Python 正则表达式:将字符串中的所有 url 替换为 <img> 和 <a> 标签



我有一个字符串,其中包含一些页面和图像的许多URL:

La-la-la https://example.com/ la-la-la https://example.com/example.PNG

我需要将其转换为:

La-la-la <a href="https://example.com/">https://example.com/</a> la-la-la <img src="https://example.com/example.PNG">

图像格式是不可预测的,它们可以是.png.JPEG等,并且每个字符串可以多次找到任何链接

我知道这里有一些奇怪的javascript示例,但我不知道如何将它们转换为python

但我发现这是一个起点:

url_regex = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/igimg_regex = /^ftp|http|https?://(?:[a-z-]+.)+[a-z]{2,6}(?:/[^/#?]+)+.(?:jpe?g|gif|png)$/ig

Big thx寻求帮助

如果需要,可以在没有regex的情况下完成此操作。

stng = 'La-la-la https://example.com/ la-la-la https://example.com/example.PNG'
sentance = '{f_txt} <a href="{f_url}">{f_url}</a> {s_txt} <img src="{s_url}">'
f_txt, f_url, s_txt, s_url = stng.split()
print(sentance.format(f_txt=f_txt, f_url=f_url, s_txt=s_txt, s_url=s_url))

输出

La-la-la <a href="https://example.com/">https://example.com/</a> la-la-la <img src="https://example.com/example.PNG"> 

您可以使用以下正则表达式:

(https?.*?.com/)(s+[w-]*s+)(https?.*?.com/[w.]+)

  • (https?.*?.com/)第一捕获组。捕获httphttps,直到.com和正斜杠/的任何内容
  • (s+[w-]*s+)第二捕获组。捕获空白、字母数字字符和hypens以及空白。如果需要,可以向字符集中添加更多字符
  • (https?.*?.com/[w.]+)第三捕获组。捕获扩展名的httphttps.com以下的任何字符、正斜杠/、字母数字字符和句号.。同样,如果您需要其他字符,则可以向该捕获组中的字符集添加更多字符

您可以在此处实时测试正则表达式。

或者,如果您希望使用可变url和域,您可以使用:

(w*:.*?.w*/)(s+[w-]*s+)(w*:?.*?.w*/[w.]+)

其中,第一个和第三个捕获组现在确实匹配后面跟着冒号:的任何字母数字字符,以及直到.的任何字符、字母数字字符w和正斜杠。你可以在这里测试。

您可以将捕获的组替换为:

<a href="1">1</a>2<img src="3">

其中,123分别是对捕获组一、二和三的反向引用。


Python代码段:

>>import re
>>str = "La-la-la https://example.com/ la-la-la https://example.com/example.PNG"
>>out = re.sub(r'(https?.*?.com/)(s+[w-]*s+)(https?.*?.com/[w.]+)',
r'<a href="1">1</a>2<img src="3">',
str)
>>print(out)
La-la-la <a href="https://example.com/">https://example.com/</a> la-la-la <img src="https://example.com/example.PNG">

最新更新