Search code examples
postgresqlregexp-replace

Postgresql Regexp_replace group


Sorry my english

i have this query

select regexp_replace('Hello OBLIG: 451451, world OBLIG: 12123456789, Task OBLIG: 789456123, world ', '(OBLIG: )([^,]*)', '\1\2' , 'g')

I need to return something like this

Hello OBLIG: 1451, world OBLIG: 6789, Task OBLIG: 6123, world

the number after "OBLIG:" should be the last 4 digits

Any idea?


Solution

  • You were almost there.

    select regexp_replace(
        'Hello OBLIG: 451451, world OBLIG: 12123456789, Task OBLIG: 789456123, world ', 
        '(OBLIG: )([[:digit:]]*)([[:digit:]]{4})', '\1\3' ,
        'g'
    );
    

    Of course, this assumes you always have at least 4 digits in each number.