gpt4 book ai didi

python - 替换Python中的出现

转载 作者:行者123 更新时间:2023-12-01 02:42:02 26 4
gpt4 key购买 nike

我有一个字符串,该字符串可能包含一些出现的内容,例如:

http://site/image.jpg

当出现这种情况时,用

替换这种情况的正确方法是什么

<img src="http://site/image.jpg">

真正重要的是仅替换以http开头的出现。结尾为 .jpg , .pnggif通过<img> HTML 标签。

因此,如果所有文本中存在任何图像的 URL 链接,则会通过 HTML 标记对其进行格式化以显示图像。

最佳答案

使用正则表达式非常简单:

import re

string = 'some other text, a URL http://site/image.jpg and other text'

print(re.sub(r'(https?.+?(?:jpg|png|gif))', r'<img src="\1">', string))

# some other text, a URL <img src="http://site/image.jpg"> and other text

(https?.+(?:jpg|png|gif))匹配以 http 开头的所有内容或https并以 jpg 结尾, pnggif

'<img src="\1">'这里是\1指前一个正则表达式中的第一个(也是唯一一个)捕获组(包含图像 url)。

关于python - 替换Python中的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45590936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com