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

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

    Expanding on the solution by Pat Notz a bit, I found it even the more elegant to:
      - name the methods the same as re provides (e.g. search() vs. check()) and
      - implement the necessary methods like group() on the holder object itself:

    class Re(object):
        def __init__(self):
            self.result = None
    
        def search(self, pattern, text):
            self.result = re.search(pattern, text)
            return self.result
    
        def group(self, index):
            return self.result.group(index)
    

    Example

    Instead of e.g. this:

    m = re.search(r'set ([^ ]+) to ([^ ]+)', line)
    if m:
        vars[m.group(1)] = m.group(2)
    else:
        m = re.search(r'print ([^ ]+)', line)
        if m:
            print(vars[m.group(1)])
        else:
            m = re.search(r'add ([^ ]+) to ([^ ]+)', line)
            if m:
                vars[m.group(2)] += vars[m.group(1)]
    

    One does just this:

    m = Re()
    ...
    if m.search(r'set ([^ ]+) to ([^ ]+)', line):
        vars[m.group(1)] = m.group(2)
    elif m.search(r'print ([^ ]+)', line):
        print(vars[m.group(1)])
    elif m.search(r'add ([^ ]+) to ([^ ]+)', line):
        vars[m.group(2)] += vars[m.group(1)]
    

    Looks very natural in the end, does not need too many code changes when moving from Perl and avoids the problems with global state like some other solutions.

提交回复
热议问题