Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex replace using pattern

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading