criz
criz

Reputation: 273

Is it possible to substitute adjacent characters in a string using regex if count is 2?

String: abc aa efg a aaa hijk aazzz

Using regex, I would like to substitute only the 2 adjacent "a" into a single "a".

  1. aa to a
  2. aazzz to azzz

My code is this but it also substitutes the 3 "a".

s/(aa)/a/g;

Upvotes: 1

Views: 42

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

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

Demo

Upvotes: 3

Related Questions