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.
CodePudding user response:
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.
CodePudding user response:
Here is a solution that is not limited to the letters 'a'
and 'b'
.
Matches of the following regular expression are to be replaced by the content of capture group 2.
(?<=(.))\1(?=\1*(.))
The regular expression is comprised of the following elements.
(?<= # begin a positive lookbehind
(.) # match any character and save to capture group 1
) # end positive lookbehind
\1 # match the content of capture group 1
(?= # begin a positive lookahead
\1* # match the content of capture group 1 zero or more times
(.) # match any character and save to capture group 2
) # end positive lookahead