Perl:通过正则表达式匹配来改变字符串

时间:2013-03-19 21:01:59

标签: regex perl

我正在使用此代码通过正则表达式匹配来更改字符串。

$a->{'someone'} = "a _{person}";
$a->{'person'} = "gremlin";

$string = "_{someone} and a thing"
while($string =~ /(_\{(.*?)\}/g){
    $search = metaquote($1);
    $replace = $a->{$2};
    $string =~ s/$search/$replace/;
}

结果是a _{person} and a thing,但我期待:a gremlin and a thing

如何使其发挥作用?

3 个答案:

答案 0 :(得分:4)

该函数名为quotemeta,而不是metaquote。此外,正则表达式中缺少右括号:

#!/usr/bin/perl
use warnings;
use strict;

my $a;

$a->{'someone'} = "a _{person}";
$a->{'person'}  = "gremlin";

my $string = "_{someone} and a thing";
while($string =~ /(_\{(.*?)\})/g){
    my $search  = quotemeta($1);
    my $replace = $a->{$2};
    $string =~ s/$search/$replace/;
}
print "$string\n";

我还添加了strictwarnings来帮助自己避免常见的陷阱。

答案 1 :(得分:2)

我认为这应该是更有效的变体:

use strict;
my $a;
$a->{'someone'} = "a _{person}";
$a->{'person'} = "gremlin";

my $string = "_{someone} and a thing";
while( $string =~ s/(_\{(.*?)\})/ $a->{$2} /ges ) {}
print $string."\n";

答案 2 :(得分:0)

此变体会反复替换字符串中占位符的所有以获取相应的哈希值,直到没有剩余为止。

此外,a是任何变量的错误标识符,因此我将其命名为tokens

use strict;
use warnings;

my %tokens = (
  someone => 'a _{person}',
  person  => 'gremlin',
);

my $string = '_{someone} and a thing';

1 while $string =~ s/_\{([^}]+)\}/$tokens{$1}/g;

print $string, "\n";

<强>输出

a gremlin and a thing