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

后端 未结 15 649
情深已故
情深已故 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 12:03

    Yeah, it's kind of annoying. Perhaps this will work for your case.

    
    import re
    
    class ReCheck(object):
        def __init__(self):
            self.result = None
        def check(self, pattern, text):
            self.result = re.search(pattern, text)
            return self.result
    
    var = 'bar stuff'
    m = ReCheck()
    if m.check(r'foo(.+)',var):
        print m.result.group(1)
    elif m.check(r'bar(.+)',var):
        print m.result.group(1)
    elif m.check(r'baz(.+)',var):
        print m.result.group(1)
    

    EDIT: Brian correctly pointed out that my first attempt did not work. Unfortunately, this attempt is longer.

提交回复
热议问题