1

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:

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.

1
  • I think you want select regexp_replace('xxxaaabc','(a+)','\1zzz','i') AS Result; (demo) Commented Oct 18, 2022 at 16:14

1 Answer 1

2

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.

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.