Search code examples
pythonswitch-statement

how can I combine a switch-case and regex in Python


I want to process a string by matching it with a sequence of regular expression. As I'm trying to avoid nested if-then, I'm thinking of switch-case. How can I write the following structure in Python? Thank you

switch str:
   case match(regex1):
       # do something
   case match(regex2):
       # do sth else

I know Perl allows one to do that. Does Python?


Solution

  • You are looking for pyswitch (disclaimer: I am the author). With it, you can do the following, which is pretty close to the example you gave in your question:

    from pyswitch import Switch
    
    mySwitch = Switch()
    
    @myswitch.caseRegEx(regex1)
    def doSomething(matchObj, *args, **kwargs):
        # Do Something
        return 1
    
    @myswitch.caseRegEx(regex2)
    def doSomethingElse(matchObj, *args, **kwargs):
        # Do Something Else
        return 2
    
    rval = myswitch(stringYouWantToSwitchOn)
    

    There's a much more comprehensive example given at the URL I linked. pyswitch is not restricted to just switching on regular expressions. Internally, pyswitch uses a dispatch system similar to the examples others have given above. I just got tired of having to re-write the same code framework over and over every time I needed that kind of dispatch system, so I wrote pyswitch.