RegEx - Return pattern to the right of a text string for URL

Viewed 231

I'm looking to return the URL string to the right of a specific set of text using RegEx:

URL:

www.websitename/countrycode/websitename/contact/thank-you/whitepaper/countrycode/whitepapername.pdf 

What I would like to just return:

/whitepapername.pdf

I've tried using ^\w+"countrycode"(\w.*) but the match won't recognize countrycode.

In Google Data Studio, I want to create a new field to remove the beginning of the URL using the REGEX_REPLACE function.

Ideally using:

REGEX_REPLACE(Page,......)
2 Answers

You could use a capturing group and replace with group 1. You could match /countrycode literally or use the pattern to match 2 times chars a-z with an underscore in between like /[a-z]{2}_[a-z]{2}

In the replacement use group 1 \\1

^.*/countrycode(/[^/]+\.\w+)$

Regex demo

Or using a country code pattern from the comments:

^.*/[a-z]{2}_[a-z]{2}(/[^/]+\.\w+)$

Regex demo

The second pattern in parts

  • ^ Start of string
  • .*/ Match until the last occurrence of a forward slash
  • [a-z]{2}_[a-z]{2} Match the country code part, an underscore between 2 times 2 chars a-z
  • ( Capture group 1
    • /[^/]+ Match a forward slash, then match 1+ occurrences of any char except / using a negated character class
    • \.\w+ Match a dot and 1+ word chars
  • ) Close group
  • $ End of string

The REGEXP_REPLACE function below does the trick, capturing all (.*) the characters after the last countrycode, where Page represents the respective field:

REGEXP_REPLACE(Page, ".*(countrycode)(.*)$", "\\2")

Alternatively - Adapting the RegEx by The fourth bird to Google Data Studio:

REGEXP_REPLACE(Page, "^.*/countrycode(/[^/]+\\.\\w+)$", "\\1")

Google Data Studio Report as well as a GIF to elaborate:

Related