首页 > 解决方案 > 如何评估 sed 风格的正则表达式

问题描述

假设用户输入是:

s/foo/bar

并且字符串是

the foo is

sed 上的输出将是the bar is,对吗?

那么,使用该re模块,我怎样才能在纯 python 中实现这一点?

标签: python

解决方案


使用re.sub和简单str.replace(使用后一种进行简单的子字符串替换以避免通过正则表达式产生的任何额外开销):

>>> import re
>>> re.sub("foo", "bar", "the foo is")
'the bar is'
>>> "the foo is".replace("foo", "bar")
'the bar is'

看来您只想替换第一个出现(因为要替换每个出现,sed 模式将是s/foo/bar/g),您可以只替换第一个foobar如下所示:

>>> re.sub("foo", "bar", "the foo is foo", 1)
'the bar is foo'
>>> "the foo is foo".replace("foo", "bar", 1)
'the bar is foo'

推荐阅读