1

I have a string that comes in different formats like these:

UserId=1;IP Address=85.154.221.54;Device Type=Chrome57
Device Type=Chrome57;IP Address=85.154.221.54
Device Type=Chrome57

How can I extract the IP Address and return empty string if there is no match ?

I have tried the following, but it return the string itself if there is no match.

select regexp_replace('Error=0;UserId=-1;IP Address=85.154.221.54;Device Type=Chrome57', '.*IP Address=(.+);.*', '\1') from dual;
Bilal Halayqa
  • 932
  • 1
  • 6
  • 25

1 Answers1

1

You may use REGEXP_SUBSTR with your slightly improved pattern:

select regexp_substr('Error=0;UserId=-1;IP Address=85.154.221.54;Device Type=Chrome57',
                     'IP Address=([0-9.]+)',
                     1, 1, NULL, 1
                    )
from dual

Here,

  • IP Address= - matches IP Address=
  • ([0-9.]+) - matches and captures into Group 1 one or more digits or/and .

See an online demo. If there is no match, the output will be NULL.

select regexp_substr('Error=0;UserId=-1;IP Address=85.154.221.54;Device Type=Chrome57',
                     'IP Address=([0-9.]+)',
                     1, 1, NULL, 1
                    ) as Result
from dual
-- => 85.154.221.54
--select regexp_substr('Error=0;UserId=-1;IP Address= Device Type=Chrome57', 'IP Address=([0-9.]+)', 1, 1, NULL, 1) as result from dual
-- => NULL

enter image description here

Note that the last 1 argument to REGEXP_SUBSTR function returns the contents of capturing group #1 (text captured with the first parenthesized part of the pattern).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563