Reputation: 273
String: abc aa efg a aaa hijk aazzz
Using regex, I would like to substitute only the 2 adjacent "a" into a single "a".
My code is this but it also substitutes the 3 "a".
s/(aa)/a/g;
Upvotes: 1
Views: 42
Reputation: 521289
Lookarounds come in handy here, and we can try matching aa
on the condition that both what comes before aa
and after it is not another a
. Use this pattern:
(?<!a)aa(?!a)
Here is a working code snippet (demo below):
my $old = 'abc aa efg a aaa hijk aazzz';
my $new = $old =~ s/(?<!a)aa(?!a)/a/rg;
print $new;
abc a efg a aaa hijk azzz
Upvotes: 3