How do you translate this regular-expression idiom from Perl into Python?

后端 未结 15 621
情深已故
情深已故 2020-12-04 11:16

I switched from Perl to Python about a year ago and haven\'t looked back. There is only one idiom that I\'ve ever found I can do more easily in Perl than in Python:<

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 11:46

    Using named groups and a dispatch table:

    r = re.compile(r'(?Pfoo|bar|baz)(?P.+)')
    
    def do_foo(data):
        ...
    
    def do_bar(data):
        ...
    
    def do_baz(data):
        ...
    
    dispatch = {
        'foo': do_foo,
        'bar': do_bar,
        'baz': do_baz,
    }
    
    
    m = r.match(var)
    if m:
        dispatch[m.group('cmd')](m.group('data'))
    

    With a little bit of introspection you can auto-generate the regexp and the dispatch table.

提交回复
热议问题