如何替换 Python 中第一次出现的正则表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3951660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:31:23  来源:igfitidea点击:

How to replace the first occurrence of a regular expression in Python?

pythonregexsearchreplace

提问by girish

I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?

我只想替换字符串中第一次出现的正则表达式。有没有方便的方法来做到这一点?

回答by Nick T

Specify the countargument in re.sub(pattern, repl, string[, count, flags])

指定count参数re.sub(pattern, repl, string[, count, flags])

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced.

可选参数 count 是要替换的模式出现的最大次数;count 必须是非负整数。如果省略或为零,则将替换所有出现的内容。

回答by eldarerathis

re.sub()has a countparameter that indicates how many substitutions to perform. You can just set that to 1:

re.sub()有一个count参数指示要执行多少次替换。您可以将其设置为 1:

>>> s = "foo foo foofoo foo"
>>> re.sub("foo", "bar", s, 1)
'bar foo foofoo foo'
>>> s = "baz baz foo baz foo baz"
>>> re.sub("foo", "bar", s, 1)
'baz baz bar baz foo baz'

Edit: And a version with a compiled SRE object:

编辑:以及带有编译的 SRE 对象的版本:

>>> s = "baz baz foo baz foo baz"
>>> r = re.compile("foo")
>>> r.sub("bar", s, 1)
'baz baz bar baz foo baz'