I need to replace a pattern matched by regex with another pattern using regex, in C++.
Example –
We have the following characters: "a" and "b"
I want to replace like this –
Original text –
aabaaaaaaabaaabab
Replacement –
abbabbbbbbbabbbab
Replace logic –
"aab" must be replaced by "abb",
"aaab" must be replaced by "abbb",
"aaaab" must be replaced by "abbbb",
and so on…
I found the following regex for getting the matches –
aa+b
What regex replace pattern must be applied to get the desired replacement?
Thanks.
>Solution :
If using lookarounds be a possibility for you, here is one solution. Match on the following pattern:
(?<=a)a(?=a*b)
and then replace with just a single b. The pattern says to match:
(?<=a) assert that at least one 'a' precedes (i.e. ignore first 'a')
a a letter 'a'
(?=a*b) which is following by zero or more 'a' then a 'b'
Here is working demo.