0

So I'm new to regex and trying to write a regex that will match this:

example.com/some-url-text-here/

but not something like

example.com/some-url-text/but-also-more-than-two-slashes/
example.com/text-here/one-slash-too-many/two-slashes-too-many/

Basically, I would like it to match a url that has some string-separated-by-dashes surrounded by no more than two /'s.

I tried a couple of different things like negative look around or not.... last thing I tried was this:

example\.com/[a-zA-z]*-*/

[a-zA-z]*-* matches something like text-here, but I can't get it to match /text-here/.. what am I doing wrong in this case?

ocean800
  • 3,489
  • 13
  • 41
  • 73

3 Answers3

2

try regex below with lookahead, it will asserted no more backslash come after the 2nd

example\.com\/[a-zA-Z-]+[a-zA-Z]\/(?!.*\/)

demo

Skycc
  • 3,496
  • 1
  • 12
  • 18
  • Ah, thanks for showing how it works with the lookahead! For the above regex, I just put a `$` at the end :) – ocean800 Jun 21 '17 at 18:27
1

If you have problems with regexen, you could simply split around "/", make sure that the elements aren't empty (except possibly the last one) and that there aren't more than 3 elements.

You can use -1 as parameter, to make sure the last elements are split:

>>> "some/url//".split("/", -1)
['some', 'url', '', '']
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

The reason your regex isn't working is because of the order you have it in.

example\.com/[a-zA-z]*-*/

This is looking for text UPPER and lower and THEN hyphens. Just include the hyphens in the brackets like so:

example\.com/[a-zA-z-]*/
double_j
  • 1,636
  • 1
  • 18
  • 27