How to check urls againts a predefined list of regex rules in order to get a match in python? -
i'm trying match url request have literal components , variable components in path list of predefined regex rules. similar routes python library. i'm new regex if explain anchors , control characters used in regex solution appreciate it.
assumming have following list of rules. components containing : variables , can match string value.
(rule 1) /user/delete/:key (rule 2) /user/update/:key (rule 3) /list/report/:year/:month/:day (rule 4) /show/:categoryid/something/:key/reports
here example test cases show request urls , rules should match
/user/delete/222 -> matches rule 1 /user/update/222 -> matches rule 2 /user/update/222/bob -> not match rule defined /user -> not match rule defined /list/report/2004/11/2 -> matches rule 3 /show/44/something/222/reports -> matches rule 4
can me write regex rules rule 1,2,3,4 ?
thank you!!
i'm not sure why need regex that. can split , count:
if len(url.split("/")) == 4: #
you make sure length 4 because there's additional element @ beginning empty string.
of using like:
if url.count("/") == 3: #
if want use regex, them maybe use this:
if re.match(r'^(?:/[^/]*){3}$', url): #
as per edit:
you use 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 beginning of string. $
matches end of string. together, make sure string testing begins , ends regex; there's nothing before or after 'template'.
[0-9]
matches 1 digit.
+
quantifier. allow repetition of character or group before it. [0-9]+
means 1 or more digits.
{4}
fixed quantifier. bit +
, repeats 4 times. {1,2}
variation of it, means between 1 , 2 times.
all other characters in regex above literal characters , match themselves.
Comments
Post a Comment