-1

enter code here I have following URLs (part of). Among them I need to get the details after final "/"

/magasins/vos-magasins/le-bhv-marais
/magasins/vos-magasins/le-bhv-marais-homme
/magasins/vos-magasins/bhv-marais-parly2
/magasins/le-bhv-marais-la-niche
/magasins/vos-magasins/mobicity-au-bhv-marais
/magasins/vos-magasins/gucci-au-bhv-marais

I know how to match all the part as follows

/magasins/[a-z-]+/?[a-z0-9-]+

But I need to get last part after the final "/".

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
user
  • 145
  • 1
  • 2
  • 12

1 Answers1

0

This regex will work for you:

(?<=\/)[a-z0-9-]+?$

Regex demo

Explanation:

(?<= ) lookbehind finds a pattern to start your match (but will not include this inside your matching group).

\/ matches a literal /

[a-z0-9-] matches a character that's alphanumeric, or hyphen -

+? that character must occur one or more times until next pattern

$ end of input

Since not all browsers support lookbehind, I've also provided this version for javascript:

var regex = /\/([a-z0-9-]+)$/

match = "/magasins/vos-magasins/le-bhv-marais".match(regex); 
console.log(match[1]); // le-bhv-marais

match = "/magasins/vos-magasins/le-bhv-marais-homme".match(regex);
console.log(match[1]); // le-bhv-marais-homme

match = "/magasins/vos-magasins/bhv-marais-parly2".match(regex);
console.log(match[1]); // bhv-marais-parly2

match = "/magasins/le-bhv-marais-la-niche".match(regex);
console.log(match[1]); // le-bhv-marais-la-niche

match = "/magasins/vos-magasins/mobicity-au-bhv-marais".match(regex);
console.log(match[1]); // mobicity-au-bhv-marais

match = "/magasins/vos-magasins/gucci-au-bhv-marais".match(regex);
console.log(match[1]); // gucci-au-bhv-marais
Community
  • 1
  • 1
chatnoir
  • 2,185
  • 1
  • 15
  • 17
  • here "?" means optional of + – user May 23 '19 at 10:31
  • when added to `+`, `+?` means one or more times but *lazy* match, meaning it will repeat as few times as possible while remaining true. Without `?`, the `+` alone is *greedy*, meaning it will repeat as many times as possible. In this example it probably doesn't make a difference and you can safely omit the `?`. – chatnoir May 23 '19 at 10:37
  • I've also updated answer to work with most browsers (not requiring lookbehind) – chatnoir May 23 '19 at 10:49
  • @user You're most welcome! – chatnoir May 23 '19 at 11:51