-1

I have a url that looks like this: www.example.com/website/link1/link2/link3

Which regex expression can I use to only get link3?

I found something similar but can't get it to work. I need to ignore the www.example.com/website/

 ^\/[^/]+\/([^/]+)\/
user1084561
  • 115
  • 2
  • 3
  • 11

2 Answers2

1

Your URL doesn't end in a slash, so you can simply capture the last chunk of content leading up to the final trailing slash:

/([^\/]+)$/

Note that you need the \ before the / to escape it, since it's embedded in / wrappers and some environments won't allow the embedded / without a preceding \.

If you need to support a trailing slash, you can add \/? ("an optional slash") before the $.

An example demo of this regex (with a useful explanation about it) can be found here: https://regex101.com/r/hRR4rw/1

Sean Werkema
  • 5,810
  • 2
  • 38
  • 42
0

Normally you just anchor to the end:

/([^/]+)\/?$/

Where that matches /link/example/ as well as /link/example and returns example in both cases.

tadman
  • 208,517
  • 23
  • 234
  • 262