python - 如何使用 `re.sub()` 替换 str 的一部分?

标签 python regex python-2.7 regex-lookarounds

我可以将 oldText 替换为 newText1 作为 re.sub("'(.*)'", 'newText', "test = 'oldText' ”) 但我尝试使用 re.sub() 作为 re.sub("'test = (.*)'", 'newText', "test = 'oldText'")

我可以以模式传递实际文本吗?

我认为数字是不好的例子,我用 str 更新了。第一个有效,但第二个无效。模式中不允许有实际文本吗?

最佳答案

>>> import re
>>> 
>>> re.sub(r"(test = )'.*'", r"\1'" + str(22) + r"'", "test = '21'")
"test = '22'"

您可以做到这一点,但您需要捕获比赛的所有其他部分,并将其与新结果拼凑在一起。

关于python - 如何使用 `re.sub()` 替换 str 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35236120/

相关文章:

python getattr 内置方法执行默认参数

python-2.7 - Python 2.7 bool 运算符逻辑

javascript - 用于连续/嵌套正则表达式的 Google Sheets 脚本

python - 正则表达式: Removing this [##### : #####] from a string

python - Django,自定义模板过滤器 - 正则表达式问题

python - 如何从 QThread 和 Queue 运行的函数返回值

python - zipimport.ZipImportError : bad local file header caused by zip caching bug?

python - 轮子有什么用,为什么它们对安装包有帮助?

python - 如何使用 simple_salesforce 更新嵌套对象?

python - 如何从网址中提取标题?