Remove all consecutive repeated characters using Regular Expression.
In Javascript this works well:
txt='aaa bbb 888 bbb ccc ddd'.replace(/(?!(?!(.)\1))./g,'');
Returns 'a b 8 b c d'
How can I do it with Posgresql regexp_replace function? This won't work:
SELECT regexp_replace('aaa bbb 888 bbb ccc ddd',E'(?!(?!(.)\\\\1)).','g');
$ psql -c "SELECT regexp_replace('aaa bbb 888 bbb ccc ddd',E'(?!(?!(.)\\1)).','g');"
regexp_replace
-------------------------
aaa bbb 888 bbb ccc ddd
(1 row)
$ psql -c "SELECT regexp_replace('aaa bbb 888 bbb ccc ddd','(?!(?!(.)\1)).','g');"
ERROR: invalid regular expression: invalid backreference number
What am I doing wrong?
There's a similar SO question that can help you to get the answer:
SELECT regexp_replace('aaa bbb 888 bbb ccc ddd', '(.)\1{1,}', '\1', 'g');
regexp_replace
----------------
a b 8 b c d
(1 row)
It uses a backreference to capture the groups of repeating characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With