如何替换 Python 中第一次出现的正则表达式? [英] How to replace the first occurrence of a regular expression in Python?

查看:73
本文介绍了如何替换 Python 中第一次出现的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

<预><代码>>>>s = "foo foo foofoo foo">>>re.sub("foo", "bar", s, 1)'酒吧富富富富'>>>s = "baz baz foo baz foo baz">>>re.sub("foo", "bar", s, 1)'baz baz bar baz foo baz'

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

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

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

解决方案

re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 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:

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

这篇关于如何替换 Python 中第一次出现的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆