【发布时间】:2017-12-09 07:41:21
【问题描述】:
我在执行全局匹配时遇到了问题。如何将匹配的字符串替换为由原始字符串和新字符串组成的新字符串。字符串是这样的:
$string = "t123:apple;t456:pear;t789:banana";
然后我有一个这样的哈希:
my %hash = (
t123 => 'fruit1',
t456 => 'fruit2',
t789 => 'fruit3',
);
我怎样才能获得一个新的字符串,例如:
$newstring = "t123 fruit1:apple;t456 fruit2:pear;t789 fruit3:banana";
现在,我的 perl 代码是:
while($string =~ /t\d{3}/g){
if (exists $hash{"$&"}) {
my $match = $&;
$string =~ s/$&/$match.$hash{"$&"}/;
}
}
但它不起作用,因为匹配总是从第一个字符开始。我想我应该使用pos(string) 或其他东西让它有一个偏移量,但我不知道该怎么做。
【问题讨论】:
标签: regex perl match substitution