python - 如何用python替换字符串中的字符串?

标签 python python-3.x

我有一个很长的字符串,其中包含标签 img 和属性 src,但现在我想使用正则表达式删除 src 中的一些字符串.

我尝试过以下代码,但我认为pattern中有一些错误。

#!/usr/bin/env python
#encoding: utf-8
import re
url = "<p><img src ='https://xxx.cn/20190504195124718.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2gzNTYzNjM=,size_16,color_FFFFFF,t_70'></img></p><p><img src ='https://xxxx.cn/20190504195124718.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2gzNTYzNjM=,size_16,color_FFFFFF,t_70'></img></p>"

pattern = re.compile(r"https://img-.*(\?x-oss-process.*t_70)")

print(pattern.findall(url))

out = re.sub(pattern, '', url)

print(out)

第一次打印,得到结果:

['?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2gzNTYzNjM=,size_16,color_FFFFFF,t_70']

第二次打印,得到结果:

<p><img src =''></img></p>

我想获取img src删除字符串的新字符串?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2gzNTYzNjM= ,size_16,color_FFFFFF,t_70,只有“https://xxx.cn/20190504195124718.png ”。

就像:

url = "<p><img src ='https://xxx.cn/20190504195124718.png'></img></p><p><img src ='https://xxxx.cn/20190504195124718.png'></img></p>"

如何编写模式

非常感谢~

最佳答案

由于您需要替换字符串,我们将使用捕获组 (?#...)

output = re.sub("(?#<img.*)\?x-oss-process.*?t_70",'',url)

添加了?在 t_70 之前进行非贪婪匹配,它将捕获多个 img 标签。

来自文档

(?#...)
A comment; the contents of the parentheses are simply ignored.

请参阅[此处]文档 ( https://docs.python.org/2/library/re.html )

关于python - 如何用python替换字符串中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007673/

相关文章:

python - 将 for 循环的数组结果存储在字典中

python - App Engine - 在运行时指定实体名称

Python Pandas isin 返回索引

python - 如何在不覆盖父函数的情况下将值返回给父类(super class)?

python-3.x - 自定义 Bokeh 中文本悬停框的大小

python - 如何限制python函数的参数必须是字符串或lambda表达式之类的函数

python - 如何找到列表中项目的索引,这些项目存在于另一个列表中?

python - 当矩阵a是二维矩阵,b是三维矩阵时,如何理解matmul函数?

python - "The set of methods, however, is fixed when the class is first defined"是真的吗?

python - 薛定谔字典: getting values for dynamic keys on indirect access