您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中匹配组

在Python中匹配组

您可以创建一个小类,该类返回调用match的布尔结果, 保留匹配的组以供后续检索:

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作为函数的更新,以及Python 3.8赋值表达式-现在不需要REMatcher类:

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()
python 2022/1/1 18:30:45 有202人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶