Python正则表达式:用<img/>和<a> tags

时间:2018-07-13 14:16:17

标签: python regex replace

I have a string with many urls to some pages and images:

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

And I need to convert it to:

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

Image formats are unpredictable, they can be .png .JPEG etc., and any links can be found multiple times per string

I understand, that there are some strange javascript examples here, but I can not get how to convert them to python.

But I found this as a starting point:

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

Big thx for help

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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

  • (https?.*?\.com\/)第一个捕获组。捕获httphttps(不超过.com的所有内容并使用正斜杠/
  • (\s+[\w-]*\s+)第二个捕获组。捕获空格,字母数字字符和连字符以及空格。您可以根据需要在字符集中添加更多字符。
  • (https?.*?\.com\/[\w\.]+)第三捕获组。捕获httphttps,不超过.com的任何内容,正斜杠/,字母数字字符和扩展名.。同样,如果需要其他字符,可以在此捕获组的字符集中添加更多字符。

您可以实时测试正则表达式here

或者,如果您希望使用可变的网址和域,则可以使用:

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