0

I have an expression like so:

Select regexp_replace('Seattle, WA Se', 'Se', 'SE')

I want to replace the 'Se' with 'SE' but don't want to touch the word 'Seattle'. So far, both 'Seattle' and 'Se' get changed to 'SEattle' and 'SE'.

How do I add a condition in the RegExp_Replace expression to find and change on the "stand-alone" 'Se'?

Thanks.

2 Answers 2

1

How do I add a condition in the RegExp_Replace expression to find and change on the "stand-alone" 'Se'?

Search for a preceding space character (or start-of-the-string) then Se then a following space character (or end-of-the-string) and use back references to maintain the preceding and following space characters in the replacement string:

SELECT REGEXP_REPLACE(
         'Seattle, WA Se',
         '(^|\s)Se(\s|$)',
         '\1SE\2'
       )
FROM DUAL;
Sign up to request clarification or add additional context in comments.

2 Comments

When I first looked at your answer, I thought, why are you not using word anchors? I did not know that Oracle database does not include this in its reg expression engine.
@PatrickBacon If it did then it would make life so much easier - especially if trying to match Se Se Se - which this answer has issues with (but can be fixed by, first, inserting a repeat of each white space character then, secondly, doing the above replacement and then, finally, removing each repeated white space; however, that's a lot of work which could just easily be solved by the zero-width word-boundary match).
0

Change your regular expression to

'Se$'

$ binds to the end-of-string, so 'Se$' means that 'Se' must appear at the end of the string with no characters after it. This will let the trailing Se be matched, but the Se in Seattle won't be.

Best of luck.

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.