python - 如何评估 sed 风格的正则表达式
问题描述
假设用户输入是:
s/foo/bar
并且字符串是
the foo is
sed 上的输出将是the bar is
,对吗?
那么,使用该re
模块,我怎样才能在纯 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
),您可以只替换第一个foo
,bar
如下所示:
>>> 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'
推荐阅读
- php - 用户自定义帖子类型 Wordpress 仅创建一项
- python - 恢复已训练的模型时出错
- javascript - 在 ReactJS 中构建响应式页脚
- amazon-web-services - 连接到在 EC2 实例上运行的 jupyter 笔记本时出现问题
- bash - 在bash中调用函数时“找不到命令”
- visual-studio - Visual Studio 可扩展性 (VSX) - 获取当前分支名称
- ros - 在发布者和订阅者之间同步
- database - 在开发和生产中使用不同的教义.yaml 文件与 Symfony4
- jmeter - Jmeter sometimes shows "WARN c.h.c.r.e.LoggingCSSParseErrorHandler:" message while running the script
- javascript - React JS如何在数组内显示带有数组的JSON