0

I am working with urls. I need to find a regex that catches strings like this:

string/string/ -OR- string/string

But there is an exception. The first string cannot be "brand" nor "category" (but the second can be).

The second forward slash is optional.

So these are valid strings:

string/string-2
string/yes/
string/brand   <--- "brand" or "category" can be after the first slash but not before
string/category/  <--- "brand" or "category" can be after the first slash but not before
the-string/hello
the-string/the-string-2/

These are invalid strings:

hello <--- Only 1 string, has to be 2, not good
hello/ <--- Only 1 string, has to be 2, not good
brand/string   <--- contains "brand" before the first slash, not good
brand/the-string/   <--- contains "brand" before the first slash, not good
category/string/   <--- contains "category" before the first slash, not good
category/hello   <--- contains "category" before the first slash, not good
hey/hello/world <--- Too many strings (3),only 2 needed, not good. ***THIS IS WHERE I AM STUCK***

So far I am trying this:

^(.*\b(?<!\bbrand|categories))/(.*)?

But it is still catching 3 strigs, like this "hey/hello/world", I need only two (string/string -OR- string/string/)

Please help!

karlosuccess
  • 843
  • 1
  • 9
  • 25
  • 2
    Use `^(?!brand|category)[^\/]+\/[^\/]+\/?$`. Demo: https://regex101.com/r/jSSwCW/1 – 41686d6564 stands w. Palestine Sep 10 '22 at 22:19
  • 1
    Is the input the *entire* input, or is it *part* or the input (eg `"Some text string/string some more text"`)? – Bohemian Sep 10 '22 at 22:49
  • @Bohemian That is the entire input, I need to match foo/bar/. Last forward slash optional, and the first word cannot be "brand" or "category". Cannot be 3 words either like foo/bar/hehe is invalid – karlosuccess Sep 10 '22 at 23:18
  • @41686d6564standsw.Palestine Thank you very much. It is working. I thought it was not working for me because I needed to add the parenthesis so the matches were returned in my function, like this: `^((?!brand|category)[^\/]+)\/([^\/]+)\/?$` I really appreciate the help and enlighten. – karlosuccess Sep 12 '22 at 08:20
  • @41686d6564standsw.Palestine This absolutely works for me! But sorry to be a pain, I always want to make is as robust as possible. I noticed regex is also ruling out strings like for example "brands1/canon". Because it contains the word "brand" in it. Is there a way to rule out only exactly "brand", so "brands1/canon" would be rightfully matched? I hope I make sense! Thank you – karlosuccess Sep 12 '22 at 08:24
  • @karlosuccess Yes, just add a forward slash: `^(?!brand\/|category\/)` or `^(?!(?:brand|category)\/)`. – 41686d6564 stands w. Palestine Sep 12 '22 at 08:48

0 Answers0