Home > Back-end >  Regex - expression contaning two words in site url
Regex - expression contaning two words in site url

Time:10-04

I need regex which will run on site containing both words at the same time. For example www.boots.com/**sport**/**nike** I've found in in other question something like:

^(?=.*\bnike\b)(?=.*\bsport\b).*$

Would this be correct? First word is a category so it goes between "/" chars, second word is a product name so it might appear between "-" chars.

CodePudding user response:

\b is a word boundary and matches in many more contexts than you expect. You need to restrict the context and thus you can use

^(?=.*(?:/|^)sport(?:/|$))(?=.*(?:[/-]|^)nike(?:[/-]|$)).*

Here,

  • (?=.*(?:/|^)sport(?:/|$)) - the string must contain sport at the start or immediately after / and at the end of the string or immediately followed with a / char
  • (?=.*(?:[/-]|^)nike(?:[/-]|$)) - the string must contain nike at the start or immediately after / or - and at the end of the string or immediately followed with a / or - chars.

Note you do not need $ here (that matches the end of string) as . matches any chars other than line break chars.

  • Related