2

I am trying to replace street with st only if street isn't followed by any alphabet. Replacement is allowed if after street EITHER there is non-alphabet character OR end of string.

I am trying to achieve this in Postgresql 9.5 regex_replace function. Sample query i wrote:

select regexp_replace('super streetcom','street(?!=[a-z])','st');

street here shouldn't have been replaced by st since street is followed by 'c'. So the expected output is 'super streetcom' but the output i am getting is 'super stcom'.

Any help for why i am getting the unexpected output and what can be the right way to achieve the intended result.

2
  • 1
    Are you sure (?!=pattern) is the correct negative lookahead syntax in postgresql? Usualy it is just (?!pattern) Commented Jun 30, 2017 at 11:11
  • Ohhh.. Found my mistake. negative lookahead should have been (?!pattern). Thanks @SebastianProske Commented Jun 30, 2017 at 11:14

2 Answers 2

1

A lookahead construct looks like (?!...), all what follows ?! is a lookahead pattern that the engine will try to match, and once found, the match will be failed.

It seems you need to match a whole word street. Use \y, a word boundary:

select regexp_replace('super streetcom street','\ystreet\y','st');

See the online demo

enter image description here

From the docs:

\y matches only at the beginning or end of a word

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

Comments

1

This looks like a syntax issue. Try: ?! instead of ?!= . e.g.

select regexp_replace('super street','street(?![a-z])','st');

will return

super st

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.