Can I substitute multiple items in a single regular expression in VIM or Perl?

后端 未结 7 1453
情歌与酒
情歌与酒 2020-12-02 15:57

Let\'s say I have string \"The quick brown fox jumps over the lazy dog\" can I change this to \"The slow brown fox jumps over the energetic dog\" with one regular expression

7条回答
  •  天涯浪人
    2020-12-02 16:17

    The second part of a substitution is a double quoted string, so any normal interpolation can occur. This means you can use the value of the capture to index into a hash:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    
    my %replace = (
        quick => "slow",
        lazy  => "energetic",
    );
    
    my $regex = join "|", keys %replace;
    $regex = qr/$regex/;
    
    my $s = "The quick brown fox jumps over the lazy dog";
    
    $s =~ s/($regex)/$replace{$1}/g;
    
    print "$s\n";
    

提交回复
热议问题