Greetings

There are many regex templates and one line. Seeking a reasonable way to determine which template matches a string.

At the moment, I'm running a string through the loop from the templates and checking if it matches the pattern.

import re patterns = [ (re.compile("^/upload/test/$"), "upload"), (re.compile("^/download/test/$"), "download"), (re.compile("^/test/$"), "test")] string = "/test/" for pattern in patterns: if pattern[0].match(string): print pattern[1] 

Is there a better way?

    1 answer 1

    You have chosen quite suitable way. With a cursory reading of the dzhangovsokogo urlresolvera like it becomes clear that everything is the same as yours.

    Not a big deal but it's

     patterns = [ (re.compile("^/upload/test/$"), "upload"), ... ] 

    can be changed to

     patterns = ( (re.compile("^/upload/test/$"), "upload"), ... ) 

    It seems that here it is proved that tuple (sorry, I don’t know how to translate) is faster than the list in initiation and iteration.

    • one
      Well, if so I will use this method. - Antik