是否可以编写一个可应用于多行字符串的 Python 正则表达式,并将所有出现的“foo”更改为“bar”,但仅限于以“#”开头的行?
我能够使用 Perl 的\G 正则表达式印记在 Perl 中实现此功能,它与上一场比赛的结尾相匹配。但是,Python 似乎不支持这一点。
以下是 Perl 解决方案,以防有帮助:
my $x =<<EOF;
# foo
foo
# foo foo
EOF
$x =~ s{
( # begin capture
(?:\G|^\#) # last match or start of string plus hash
.*? # followed by anything, non-greedily
) # end capture
foo
}
{$1bar}xmg;
print $x;
当然,正确的输出是:
# bar
foo
# bar bar
这可以用 Python 完成吗?
编辑:是的,我知道可以将字符串拆分成单独的行并测试每一行,然后决定是否应用转换,但请相信我的话,在这种情况下这样做并非易事。我真的需要用一个正则表达式来完成。
请您参考如下方法:
lines = mystring.split('\n')
for line in lines:
if line.startswith('#'):
line = line.replace('foo', 'bar')
不需要正则表达式。
