7

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?

8
  • 1
    select string_agg(x[1],'') from regexp_matches('aaa bbb 888 111122222 1234 bbb ccc ddd','(.)\1*','g') t(x); Commented Aug 16, 2016 at 7:46
  • @Abelisto This returns a b 8 12 1234 b c d, which isn't exactly what the OP wanted, but I upvoted your comment because it is close. Commented Aug 16, 2016 at 7:49
  • 1
    @TimBiegeleisen It is because different input to test some more use cases. Commented Aug 16, 2016 at 7:52
  • 1
    @TimBiegeleisen To get the first character of every word (not just delete repeated characters): select string_agg(x,'') from unnest(array(select regexp_matches('aaa bbb 888 111122222 1234, bbb ccc ddd','\m(\w)\w*(\W*)','g'))) t(x); Commented Aug 16, 2016 at 8:23
  • 1
    @Abelisto - You should put this down as an answer. Your first comment perfectly solves the problem. Commented Nov 28, 2016 at 5:35

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.