简体   繁体   English

正则表达式搜索并替换为Perl中的变量

[英]Regexp search and replace as variables in Perl

I can't find a solution to this and its driving me crazy! 我找不到解决方案,这使我发疯!

my $foo = qr/(\S+) (\X+)/;
my $bar = qr/$2/;

line =~ s/$foo/$bar/g 

My problem is that $bar uses a previously defined value of $2 rather than the (\\X+) . 我的问题是$bar使用先前定义的$2值,而不是(\\X+)

Please note that second part of s is not regex, but rather string to replace regex found. 请注意, s第二部分不是regex,而是用来替换找到的regex的字符串。 You can achieve what you want with this (note ee double-eval option at the end): 您可以使用此实现您想要的(最后请注意ee double-eval选项):

my $foo = qr/(\S+) (\X+)/;
my $bar = '$2';             # no interpolation

$line =~ s/$foo/$bar/gee;   # first eval make $bar -> '$2', second replaces it 

I guess value of $bar should just be a string and not a regex. 我猜$ bar的值应该只是字符串而不是正则表达式。 The qr// doesn't look right there. qr //看起来不正确。

Similar to bvr's suggestion you can use a sub ref for the replacement side of s/// . 与bvr的建议类似,您可以在s///的替换侧使用sub ref。 This has the advantage of being precompiled (both the sub ref, and the substitution) as opposed to being recompiled for each match. 相对于为每个匹配重新编译,它具有预编译(子引用和替换)的优点。 In most cases this will be faster and more likely to catch any errors at compile time. 在大多数情况下,这样做会更快,并且更有可能在编译时捕获任何错误。

my $foo = qr/(\S+) (\X+)/;
my $bar = sub { $2 }; # or my $bar = \&some_replace_function;

$line =~ s/$foo/$bar->()/ge;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM