How to do Perl regex with alternation and substitution

79 Views Asked by At

I wish to transform "eAlpha eBeta eGamma" into "fAlpha fBeta fGamma." Of course this is just a simplified example of more complex substitutions.

Here is my perl program:

my $data= "eAlpha eBeta eGamma";
$data=~ s/(e)(Alpha)|(e)(Beta)|(e)(Gamma)/f$2/g;
say $data;

The output is

fAlpha f f

Perl regex seems to remember the $1 but not the $2. Is there a way to use regex alternation, global substitution, and capture variables like $1, $2?

  • There are never more than 3 alternates so I could do it in three steps but wish not to.

Any help would be appreciated.

2

There are 2 best solutions below

4
sticky bit On

The capture groups go from left to right without "respecting" the |. So Beta gets captured in $4 and Gamma in $6.

But you can condense it to two groups and additionally make the first group non-capturing with ?: (or don't use a group at all, as it's just a single character, but you may have something else in there in the "real thing" that requires a group).

...
$data =~ s/(?:e)(Alpha|Beta|Gamma)/f$1/g;
...
0
Pushpesh Kumar Rajwanshi On

You an use positive look ahead using alternation and just match e and substitute it with f.

my $data = "eAlpha eBeta eGamma";
$data=~ s/e(?=Alpha|Beta|Gamma)/f/g;
print($data);

Prints,

fAlpha fBeta fGamma