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;
6
  • Empty string or is NULL fine? Commented Jan 3, 2018 at 10:00
  • both works for me Commented Jan 3, 2018 at 10:01
  • @WiktorStribiżew this is Oracle so an empty string is null. Commented Jan 3, 2018 at 10:23
  • @WilliamRobertson Actually, I have seen some questions where OP asked specifically for an "empty string". So, I just wanted to make that clear so as to avoid any further terminological and other "disputes". Commented Jan 3, 2018 at 10:24
  • @WiktorStribiżew - ah, I see what you mean now :) Commented Jan 3, 2018 at 11:11

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't work if the IP is at the end without ' ; ' , try the second string
@BilalHalayqa That is because your pattern did not account for that. Remove ; at the end, and it will.

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.