如何用pythononeliner替换Perl-oneliner regex?

2024-05-18 05:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个不使用Perl的项目中工作,我希望保持一致性。这就是为什么我想知道是否可以用Python one liner轻松地将这个方便的Perl one liner替换为Python one liner

perl -pe 's/pattern/replacement/g' <<< 'expression'

这个程序一次从STDIN读取一行,用字符串replacement替换正则表达式pattern的所有匹配项,并将(可能)修改过的行输出到STDOUT。在


Tags: 项目字符串程序stdinstdoutoneperl一致性
1条回答
网友
1楼 · 发布于 2024-05-18 05:37:11

您可以使用-c命令行选项运行re.sub,但它不会像perl那样漂亮:

python -c 'import re;print(re.sub(r"<pattern>", "<replacement>", "<string>"))'

如果您还想从STDIN获取输入,则需要sys.stdin,这也意味着import-ingsys

^{pr2}$

例如:

% python -c 'import re;print(re.sub(r"foo", "bar", "foobar"))'
barbar

% python -c 'import re,sys;print(re.sub(r"foo", "bar", sys.stdin.read()))' <<< 'foobar'
barbar

相关问题 更多 >