Reputation: 5081
If I have the string aab12a221b1
and I want to replace it with zzy12z221y1
(i.e. replace a
with z
and b
with y
), is it possible to do that with a single regular expression? Two separate expressions would be trivial (/a/g -> z
, /b/g -> y
), but I am looking for a method to accomplish this without having to run more than one regex. So far I have been unable to find any way to do this.
Specifically, I am using grepWin to do some replacements across a large amount of files, and there are four characters I need to replace with other characters. The amount of time it would take to run four instead of one is minimal and I'm not on a time limit, so this is more of a hypothetical question than anything else.
Upvotes: 2
Views: 41
Reputation: 19224
This may not solve your particular problem, but generally speaking it is possible - if you can use perl regular expressions - to pass captured groups as arguments to functions for the replacement, using the e
modifier.
%map = ("a", "z",
"b", "y");
sub get_mapping{
return $map{"$_[0]"};
}
$str=~s/([ab])/get_mapping($1)/eg;
Example running here: http://ideone.com/nVJTXk
Upvotes: 1