如何在保留原始字符串的同时对字符串执行 Perl 替换? [英] How do I perform a Perl substitution on a string while keeping the original?

查看:30
本文介绍了如何在保留原始字符串的同时对字符串执行 Perl 替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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.

另见:
perldoc perlrequick:Perl 正则表达式快速入门

SEE ALSO:
perldoc perlrequick: Perl regular expressions quick start

这篇关于如何在保留原始字符串的同时对字符串执行 Perl 替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆