Regular expression to match a certain domain and last part of URL

Viewed 121

I'm working on a redesign of a site and as part of it we've changed te URL schema, as we want to redirect all old URL to the new ones I'm struggling to get this to work

The old URL are like this

/shop/category/subcategory1/subcategory2/slug

/shop/category/subcategory3/slug

/shop/category/slug

And the new ones look like this

domain.com/new/slug

I need a regular expression to match url starting with "/shop/category" and get the last part of the url as it is the slug of the product

I can get the last part of the URL with this:

([^\/]+$)

And match the start of the URL with

^shop\/category\/

But I can't find a way to to both at the same time

Thanks!

1 Answers

You can use

^shop\/category(?:\/.*)?\/([^\/]+)$

See the regex demo. Details:

  • ^ - start of string
  • shop\/category - a shop/category string
  • (?:\/.*)? - an optional occurrence of a / char and then any zero or more chars other than line brea chars as many as possible
  • \/ - a / char
  • ([^\/]+) - Group 1: one or more chars other than a /
  • $ - end of string.
Related