Friday, July 27, 2018

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



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? Currently, I use two sets of regular expressions for this situation. (In this case, I use s/quick/slow/ followed by s/lazy/energetic/.)


Answer



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";

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...