I'm not sure why you need a regex to do something like that. You can split and count:
if len(url.split("/")) == 4:
# do something
You make sure the length is 4 because there's an additional element at the beginning which is an empty string.
Of using something like:
if url.count("/") == 3:
# do something
If you really want to use regex, them maybe you could use something like this:
if re.match(r'^(?:/[^/]*){3}$', url):
# do something
As per your edit:
You could use this for rule 1:
^/user/delete/[0-9]+$
For rule 2:
^/user/update/[0-9]+$
For rule 3:
^/list/report/[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}$
For rule 4:
^/show/[0-9]+/something/[0-9]+/reports$
^
matches the beginning of the string. $
matches the end of the string. Together, they make sure that the string you are testing begins and ends with the regex; there's nothing before or after the 'template'.
[0-9]
matches any 1 digit.
+
is a quantifier. It will allow for the repetition of the character or group just before it. [0-9]+
thus means 1 or more digits.
{4}
is a fixed quantifier. It is a bit like +
, but it repeats only 4 times. {1,2}
is a variation of it, it means between 1 and 2 times.
All the other characters in the regex above are literal characters and will match themselves.