Kyle H
Kyle H

Reputation: 3303

Oracle Regexp - replace surrounding backets, but not inner string

I'm trying to take the following string...

v VARCHAR2(100) := '<LABEL> FOR ABC';

And turn it into...

'LABEL FOR ABC'

Which seemed easy, but I can't get this done in one regexp statement. The <...> block will always start the string.

For example, my best attempt....

v := REGEXP_SUBSTR(v, '[^\<][A-Z]+[^\>][A-Z ]+')

Yields 'LABEL'.

I did manage to get this working by doing the following...

v := REGEXP_REPLACE(v, '^\<');
v := REGEXP_REPLACE(v, '\>', 1, 1);

But I was wondering if this would be possible to be done in a single regexp statement.

Thanks

Edit: I forgot to mention, I only want to remove the leading <...>. If the string was something like

<LABEL> FOR ABC <LEAVE ME>

I would want it to be...

LABEL FOR ABC <LEAVE ME>

Upvotes: 0

Views: 161

Answers (2)

Noel
Noel

Reputation: 10525

You can use REGEXP_REPLACE('<LABEL> FOR ABC <LEAVE ME>','^<(.*?)>','\1').

Pattern:

^<    --matches '<' at the beginning of the string.
.*?   --non greedy quantifier to match 0 or more characters within '<' and '>'. 
      --This is enclosed in brackets to form first capture group.
      --This is then used in replace_string as \1.
>     --Matches the first '>' after the first '<'.

Example:

SELECT '<LABEL> FOR ABC <LEAVE ME>' str,
       REGEXP_REPLACE ('<LABEL> FOR ABC <LEAVE ME>', '^<(.*?)>', '\1') replaced_str
  FROM DUAL;

str                         replaced_str
----------------------------------------------------
<LABEL> FOR ABC <LEAVE ME>  LABEL FOR ABC <LEAVE ME>

Upvotes: 2

Tobsey
Tobsey

Reputation: 3400

You just want to replace all instances of <and >with an empty string? Then this:

SELECT
  REGEXP_REPLACE('<LABEL> blah', '[<>]', '') FROM DUAL

Upvotes: 1

Related Questions