regex - Perl:使用 s/(替换)并返回新字符串

标签 regex perl replace

这个问题在这里已经有了答案:





How do I perform a Perl substitution on a string while keeping the original?

(8 个回答)


2年前关闭。




在 Perl 中,运算符 s/用于替换字符串的一部分。现在s/将更改其参数(字符串)。但是,我想在打印之前替换字符串的一部分,如

print "bla: ", replace("a","b",$myvar),"\n";

有没有这样的replace Perl 中的函数,还是其他方法? s/在这种情况下不会直接工作,我想避免使用辅助变量。有什么办法可以在线进行吗?

最佳答案

require 5.013002; # or better:    use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";

perl5132delta :

The substitution operator now supports a /r option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.


my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'

关于regex - Perl:使用 s/(替换)并返回新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3440363/

相关文章:

c# - 正则表达式拆分包含标记的文本

regex - swiftlin 开括号规则

javascript - 在没有任何内置方法的情况下对字符串进行排序

java - 从字符串中删除所有不在白名单上的字符

regex - Tcl列表输出修改

ruby-on-rails - 将脚本 src 转换为 Rails 中的快速 '//= require' 语句

perl - 使用 perl 在多个文件中进行搜索和替换时保留时间戳

perl - 如何用同一行前面的文本替换单词?

java - 在 perl 脚本中执行批处理文件时需要提供参数的帮助

vim - 全局将所有 ^M 替换为换行符