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

Regular expression to capture alias in a string to be used in an oracle query without capturing characters that are the same as the alias

I have a string that will be used in an oracle query that I need to parse and change the alias of the columns in the string to a different value and I need to use a regular expression to do so.

Here is an example of the sort of string I will be dealing with:

ph.activity = ''ph.activity.1'' AND ((ph.activity = ''ph.act.1'' AND ph.activity = ''test.ph.act.1'' AND ph.activity = ''ph.test.23''))

I need to change all the ph. in the string where the ph. appears at the start of the string, where it appears after a ( character and where it appears after a whitespace and not any others.

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

So far for my regular expression I have this:

(^ph\.)|( ph.)|(\(ph.)

This doesn’t work for me as it also captures the whitespace character preceding the ph. as well as the ( character preceding its ph.

How can I modify this expression to capture the ph. without also capturing the ( and whitespace character?

>Solution :

You could change the pattern to have a single capturing group that allows start-anchor, opening parenthesis or space:

'(^|\(| )ph\.'

and in the replace string, prefix your value with \1 so it includes whatever that matched.

For example:

select regexp_replace(
  'ph.activity = ''ph.activity.1'' AND ((ph.activity = ''ph.act.1'' AND ph.activity = ''test.ph.act.1'' AND ph.activity = ''ph.test.23''))',
  '(^|\(| )ph\.',
  '\1TEST.') as result
from dual
RESULT
TEST.activity = ‘ph.activity.1’ AND ((TEST.activity = ‘ph.act.1’ AND TEST.activity = ‘test.ph.act.1’ AND TEST.activity = ‘ph.test.23’))

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