2

I need help in extracting the following string. I have tried many solutions but this one is the closest. But still not what I require. Any help is appreciated.

Sample URL: 'https://mywebsite/path/?utm_source=google&utm_medium=cpc&gclid=123abc'

Required Result:

utm_source utm_medium gclid
google cpc 123abc

The following example for gclid gives me gclid=123abc as a result, while I require to extract 123abc

SELECT l.url, REGEXP_SUBSTR(l.url, 'gclid=([^&]*)') as data
FROM mydatabase.mytable AS l
WHERE Date(l.registration_date) >= '2021-06-15'
AND REGEXP_SUBSTR(l.url, 'gclid=([^&]*)') is not null

I need to parse the other two fields also like utm_source and utm_medium.

2
  • 1
    You can try REGEXP_SUBSTR(l.url, '(?<=[?&]gclid=)[^&#]+') and similarly REGEXP_SUBSTR(l.url, '(?<=[?&]utm_source=)[^&#]+') and REGEXP_SUBSTR(l.url, '(?<=[?&]utm_medium=)[^&#]+') Commented Jun 21, 2021 at 10:23
  • 1
    gclid=12345 in sample URL but gclid=123abc in required output. Typo? Commented Jun 21, 2021 at 10:30

2 Answers 2

2

You can use lookbehinds here to exclude the static text from your matches:

REGEXP_SUBSTR(l.url, '(?<=[?&]gclid=)[^&#]+')
REGEXP_SUBSTR(l.url, '(?<=[?&]utm_source=)[^&#]+')
REGEXP_SUBSTR(l.url, '(?<=[?&]utm_medium=)[^&#]+') 

See a sample regex demo.

Details:

  • (?<=[?&]gclid=) - a positive lookbehind that matches a location that is immediately preceded with ? or & (this makes sure we only match the full query param key) and then gclid=
  • [^&#]+ - one or more chars other than & and # (consumed and returned as a match value).
Sign up to request clarification or add additional context in comments.

Comments

2
SET @URL := 'https://mywebsite/path/?utm_source=google&utm_medium=cpc&gclid=12345';
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@URL, 'utm_source=', -1), '&', 1) utm_source,
       SUBSTRING_INDEX(SUBSTRING_INDEX(@URL, 'utm_medium=', -1), '&', 1) utm_medium,
       SUBSTRING_INDEX(SUBSTRING_INDEX(@URL, 'gclid=', -1), '&', 1) gclid;
utm_source utm_medium gclid
google cpc 12345

db<>fiddle here

Comments

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.