Regex to match all before specific string if exists (GA Data Studio)

Viewed 143

I'm a bit stumped and have tried some solutions from similar posts, but Google's Data Studio does not seem to like lookbehinds.

So far I have come up with the below to match text before "/products":

.+?(?=\/products)

However I also need it to return the complete test if "/products" does not exist.

  • Eg 1:

    /sometext/somemoretext/products

should return: /sometext/somemoretext

  • Eg 2:

    /sometext/somemoretext

should return: /sometext/somemoretext

1 Answers

You can use

^(.+?)(?:/products|[?]utm|$)

See the regex demo. Details:

  • ^ - start of string
  • (.+?) - Capturing group 1: any one or more chars other than line break chars as few as possible
  • (?:/products|[?]utm|$) - a non-capturing group matching either
    • /products| - /products or
    • [?]utm - ?utm
    • | - or
    • $ - end of string.
Related