【问题标题】:Perl, global match and append something after the matched stringPerl,全局匹配并在匹配的字符串之后附加一些东西
【发布时间】: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


    【解决方案1】:

    简单的方法相当简单:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use feature 'say';
    
    my $string = "t123:apple;t456:pear;t789:banana";
    
    my %hash = (
        t123 => 'fruit1',
        t456 => 'fruit2',
        t789 => 'fruit3',
    );
    
    $string =~ s/(t\d+)/$1 $hash{$1}/g;
    
    say $string;
    

    但这并不能确保与t\d{3} 匹配的所有内容都是您哈希中的有效键。所以让我们明确地搜索这些键。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use feature 'say';
    
    my $string = "t123:apple;t456:pear;t789:banana";
    
    my %hash = (
        t123 => 'fruit1',
        t456 => 'fruit2',
        t789 => 'fruit3',
    );
    
    my $match = join '|', map quotemeta, keys %hash;
    
    $string =~ s/($match)/$1 $hash{$1}/g;
    
    say $string;
    

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 2022-01-17
      • 2012-12-30
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多