问题描述
在Perl中,有什么好方法可以使用正则表达式对字符串进行替换并将值存储在不同的变量中,而无需更改原始变量?
In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original?
我通常只是将字符串复制到新变量,然后将其绑定到对新字符串进行替换的s///
正则表达式,但是我想知道是否有更好的方法?
I usually just copy the string to a new variable then bind it to the s///
regex that does the replacement on the new string, but I was wondering if there is a better way to do this?
$newstring = $oldstring;
$newstring =~ s/foo/bar/g;
推荐答案
这是我一直用来获取字符串的修改后的副本而无需更改原始副本的惯用法:
This is the idiom I've always used to get a modified copy of a string without changing the original:
(my $newstring = $oldstring) =~ s/foo/bar/g;
在perl 5.14.0或更高版本中,您可以使用新的/r
非破坏性替换修饰符:
In perl 5.14.0 or later, you can use the new /r
non-destructive substitution modifier:
my $newstring = $oldstring =~ s/foo/bar/gr;
注意:以上解决方案也可以在不使用g
的情况下使用.它们还可以与任何其他修饰符一起使用.
Note: The above solutions work without g
too. They also work with any other modifiers.
这篇关于如何在保留原始字符串的同时对字符串执行Perl替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!