我有一个字符串,其中包含一些页面和图像的许多 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+&@#\/%=~_|])/ig
img_regex = /^ftp|http|https?:\/\/(?:[a-z\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png)$/ig
非常感谢您的帮助
如果你愿意,你可以不用 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">
我是一名优秀的程序员,十分优秀!