Python Regex:用<img>和<a>标记替换字符串中的所有url

2024-04-27 04:20:02 发布

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

我有一个包含许多指向某些页面和图像的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

大thx求助


Tags: 字符串httpscomimgpngexampleftp页面
2条回答

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

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

  • (https?.*?\.com\/)第一个捕获组。捕获httphttps,可以是.com和正斜杠/。你知道吗
  • (\s+[\w-]*\s+)第二个捕获组。捕获空格、字母数字字符和hypens以及空格。如果需要,可以向字符集添加更多字符。你知道吗
  • (https?.*?\.com\/[\w\.]+)第三捕获组。捕获扩展名的httphttps,最长.com,正斜杠/,字母数字字符和句号.。同样,如果您需要其他字符,可以将更多字符添加到此捕获组中的字符集。你知道吗

您可以测试regex livehere。你知道吗

或者,如果您需要可变的URL和域,则可以使用:

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

其中第一个和第三个捕获组现在确实匹配任何后跟冒号:的字母数字字符,以及任何高达.、字母数字字符\w和正斜杠的字符。你可以测试这个here。你知道吗

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

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

其中\1\2\3分别是对捕获的组1、2和3的反向引用。你知道吗


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">

如果您愿意,您可以在没有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"> 

相关问题 更多 >