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

后端 未结 15 632
情深已故
情深已故 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:41

    I'd suggest this, as it uses the least regex to accomplish your goal. It is still functional code, but no worse then your old Perl.

    import re
    var = "barbazfoo"
    
    m = re.search(r'(foo|bar|baz)(.+)', var)
    if m.group(1) == 'foo':
        print m.group(1)
        # do something with m.group(1)
    elif m.group(1) == "bar":
        print m.group(1)
        # do something with m.group(1)
    elif m.group(1) == "baz":
        print m.group(2)
        # do something with m.group(2)
    

提交回复
热议问题