9月中的类似问题:您如何将这种正则表达式习语从Perl转换为Python?
在模块中使用全局变量可能不是最好的方法,但可以将其转换为类:
import reclass Re(object): def __init__(self): self.last_match = None def match(self,pattern,text): self.last_match = re.match(pattern,text) return self.last_match def search(self,pattern,text): self.last_match = re.search(pattern,text) return self.last_matchgre = Re()if gre.match(r'foo',text): # do something with gre.last_matchelif gre.match(r'bar',text): # do something with gre.last_matchelse: # do something else