Search code examples
sqlpostgresqlregexp-replace

regex_replace to append to end of line?


I have a postgres table which contains rows that each hold multiple lines of text (split by new lines), for example...

The table name is formats, column is called format, an example format (1 table row) would look like the following:

list1=text1;

list2=text2;

list3=text3;

etc etc

I would like a way to identify the list2 string and then append additional text to the end of the same line.

So the outcome would be:

list1=text1;

list2=test2;additionaltext

list3=text3;

I have tried the below to try and pull in the 'capture string' into the replace string but have been unsuccessful so far.

 regexp_replace(format, 'list2=.*', '\1 additionaltext','n');

Solution

  • To capture a pattern, you must enclose it in parenthesis.

    regexp_replace(format, '(list2=.*)', '\1additionaltext', 'n')