Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres Regular Expression Positive Lookbehind with Repetition

Working for the first time with Postgres flavor regular expressions and stumped on it’s behavior here.

Input: 'xxxaaabc'

Expected: 'xxxaaazzzbc'

Logic: Match M a’s, capture group, and add ‘zzz’ directly after the sequence

Attempts:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select regexp_replace('aaabc','(?!\Sa+)','zzz','i')

Result: zzzxxxaaabc

select regexp_replace('aaabc','(?!\Sa+)','zzz','i')

Result: xxxazzzaabc

select select regexp_replace('xxxaaabc','(?!=a+)','zzz','i')

Result: zzzxxxaaabc

This one seems to get pretty close regexp_replace(‘aaabc’,'(?!\Sa+)’,’zzz’,’i’), but the repetition of a’s isn’t working.

>Solution :

Note the (?!\Sa+) pattern matches an empty location that is not immediately followed with a single non-whitespace char and then one or more a chars.

The (?!=a+) pattern matches a location in a string, that is not immediately followed with = and then one or more as.

You can capture one or more as and then use a backreference to the match and then just append the zzz:

select regexp_replace('xxxaaabc','(a+)','\1zzz','i') AS Result;

See the DB fiddle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading