Reputation: 3717
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?
Upvotes: 0
Views: 83
Reputation: 3555
try regex below with lookahead, it will asserted no more backslash come after the 2nd
example\.com\/[a-zA-Z-]+[a-zA-Z]\/(?!.*\/)
Upvotes: 2
Reputation: 1706
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-]*/
Upvotes: 1
Reputation: 54223
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', '', '']
Upvotes: 1