tags:

views:

158

answers:

1

I have a column whose values consist of a prefix and then some value, e.g.:

ABC-Car
ABC-Dog
ABC-Suit
CBR-Train

In my query I would like to trim off certain prefixes, e.g. if I trimmed off 'ABC-' it would give me the following:

Car
Dog
Suit
CBR-Train

The only problem is, all characters are valid for the part after the prefix. So it's possible I could have:

ABC-ABC-Cat

I want this trimmed value to return:

ABC-Cat

The TRIM and LTRIM functions appear to use pattern/character matching rather than once-only string matching. Is there a way to accomplish what I want with either of these functions or with another built-in function?

Currently I'm thinking I'll have to use a CASE statement to check for that prefix at the beginning of each value and if it exists, SUBSTR it off, else return the column unchanged. Hoping there is a simpler way.

+3  A: 

regexp_replace is what you'll want to use for this.

Usage examples:

select regexp_replace('ABC-Car', 'ABC-(.*)','\1') from dual; --returns 'Car'
select regexp_replace('ABC-ABC-Car', 'ABC-(.*)','\1') from dual; --returns 'ABC-Car'
select regexp_replace('ABC-ABC-Car', 'ABC-(.*)','\1') from dual; --returns 'CBR-Train'
David Oneill
Much thanks, David.
RenderIn
Be aware that regex functions are 10g+.
OMG Ponies
@Ponies, it sometimes feels like you're following me around: you make it to all the SQL questions. :) +1
David Oneill