0

I am pretty new in Regular Expression.

Input

/shop/earrings
/shop/yellow-gold-earrings
/shop/white-gold-earrings
/shop/rose-gold-earrings

/shop/necklaces
/shop/yellow-gold-necklaces
/shop/white-gold-necklaces
/shop/rose-gold-necklaces

/shop/best-buy-earrings

Regular Expression I used

\/shop\/[a-z-]*-?earrings

Desired Result

/shop/earrings
/shop/yellow-gold-earrings
/shop/white-gold-earrings
/shop/rose-gold-earrings

Actual Result

/shop/earrings
/shop/yellow-gold-earrings
/shop/white-gold-earrings
/shop/rose-gold-earrings
/shop/best-buy-earrings

I do not want /shop/best-buy-earrings to be in the result. Please help me to fix the Regular Expression. Thank you.

  • 2
    Possible duplicate of [A regular expression to exclude a word/string](https://stackoverflow.com/questions/2078915/a-regular-expression-to-exclude-a-word-string) – Ivar Oct 31 '19 at 12:17
  • 1
    `\/shop\/(?!best-buy)[a-z-]*-?earrings` – Ivar Oct 31 '19 at 12:18
  • From the [regex tag info](https://stackoverflow.com/tags/regex/info): "Since regular expressions are not fully standardized, all questions with this tag should also include a tag specifying the applicable programming language or tool." – Toto Oct 31 '19 at 13:38
  • What about `/shop/yellow-gold-best-buy-earrings` and `/shop/best-buy-gold-earrings`? – Toto Oct 31 '19 at 13:43

2 Answers2

1

Simply add gold to the regex before the - and surround with parenthesis:

\/shop\/([a-z-]*gold-)?earrings
depperm
  • 10,606
  • 4
  • 43
  • 67
1

Assuming PCRE flavour, you can use:

\/shop\/(?!best-buy)(?:\w+-)*earrings

Or, if you can use other delimiter than slash:

/shop/(?!best-buy)(?:\w+-)*earrings

Demo

Toto
  • 89,455
  • 62
  • 89
  • 125