cnil在python_在Python中匹配组
您可以創(chuàng)建一個(gè)小類,返回調(diào)用match的布爾結(jié)果,和保留匹配的組以供后續(xù)檢索:import re
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring)
return bool(self.rematch)
def group(self,i):
return self.rematch.group(i)
for statement in ("I love Mary",
"Ich liebe Margot",
"Je t'aime Marie",
"Te amo Maria"):
m = REMatcher(statement)
if m.match(r"I love (\w+)"):
print "He loves",m.group(1)
elif m.match(r"Ich liebe (\w+)"):
print "Er liebt",m.group(1)
elif m.match(r"Je t'aime (\w+)"):
print "Il aime",m.group(1)
else:
print "???"
Python 3 print as a function和Python 3.8賦值表達(dá)式的更新-現(xiàn)在不需要重新匹配類:import re
for statement in ("I love Mary",
"Ich liebe Margot",
"Je t'aime Marie",
"Te amo Maria"):
if m := re.match(r"I love (\w+)", statement):
print("He loves", m.group(1))
elif m := re.match(r"Ich liebe (\w+)", statement):
print("Er liebt", m.group(1))
elif m := re.match(r"Je t'aime (\w+)", statement):
print("Il aime", m.group(1))
else:
print()
總結(jié)
以上是生活随笔為你收集整理的cnil在python_在Python中匹配组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql半同步降级_MySQL半同步复
- 下一篇: 苹果推出 macOS Ventura 1