kennix
kennix

Reputation: 31

How to replace a character by regex in ruby

How to replace a letter 'b' to 'c' after a duplicate letter 'a' base on 2 times? for example :

ab => ab
aab => aac
aaab => aaab
aaaab => aaaac
aaaabaaabaab => aaacaabaac

Upvotes: 1

Views: 119

Answers (1)

Rahul
Rahul

Reputation: 2738

You should check groups of aa followed by b and then replace captured groups accordingly.

Regex: (?<!a)((?:a{2})+)b

Explanation:

(?<!a) checks for presence of an odd numbered a. If present whole match fails.

((?:a{2})+)b captures an even number of a followed by b. Outer group is captured and numbered as \1.

Replacement: \1c i.e first captured group followed by c.

Test String:

ab
aab
aaab
aaaab
aaaabaaabaab

After replacement:

ab
aac
aaab
aaaac
aaaacaaabaac

Regex101 Demo

Upvotes: 3

Related Questions