Nicolas Malebranche
Nicolas Malebranche

Reputation: 387

Substitute character not enclosed by brackets

I have a string containing curly brackets and I want to replace any character A, which is not contained in a pair of opening and closing brackets, by another character B. So

ABCDACD{ACDA}ABCD

should be replaced by

BBCDBCD{ACDA}BBCD

How can I do this with a regex (e.g. in Perl)? Brackets are not nested, but a solution working also for the nested case would be better.

EDIT: Changed wording

Upvotes: 0

Views: 505

Answers (2)

Håkon Hægland
Håkon Hægland

Reputation: 40748

Here is a Perl solution that does the job in steps. First it splits the string into chunks of braced/not braced items. Then does the substitution on the not-braced items, and finally puts the items back together again:

my $str = 'ABCDACD{ACDA}ABCD';
$str = do {
    my $i = 1; 
    join '', map {$i++ % 2 && $_ =~ s/A/B/g; $_ } split /(\{.*?\})/, $str 
};

Upvotes: 1

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

A similar question has already been answered before.

Perl implementation will be different in substitution evaluation part but the main idea is the same:

Match undesired context (i.e. {.*?}) or desired substring (A) (in that particular order) using alternation capturing the matches. Then substitute the undesired capture with itself and the desired one with your replacement depending on which part has matched:

my $input = "ABCDACD{ACDA}ABCD";
$input =~ s/({.*?})|(A)/{$2 ? "B" : $1}/ge;

Demo: https://ideone.com/bK4c1Y

Upvotes: 2

Related Questions