【问题标题】:How to match more regex options in the same Python function, with optional arguments?如何在同一个 Python 函数中使用可选参数匹配更多正则表达式选项?
【发布时间】:2020-05-03 16:11:17
【问题描述】:

我有这个 Python 函数:

def find_regex(regex, text, opzione2= None, opzione3 = None):
lista = []
for x in text:
    matches_prima = re.findall(regex, x)
    lunghezza1 = len(matches_prima)
    if opzione2 != None and opzione3 == None:
        matches_prima2 = re.findall(opzione2, x)
        lunghezza2 = len(matches_prima2)
        if opzione2 != None and opzione3 != None:
            matches_prima3 = re.findall(opzione3, x)
            lunghezza3 = len(matches_prima3)
lunghezza = len(matches_prima) + len(matches_prima2) + len(matches_prima3)


lista.append(lunghezza)
print("The number of {} matches is ".format(regex), sum(lista))

它应该对同一文本中的所有正则表达式匹配进行总和。但是,opzione2opzione3 是可选的,我可以有更多的可能性并包含更多的正则表达式。但是,此代码不起作用。

它被称为:

一个选项

FIND_FASE12T = re.compile(r"\]\s1\s([\w\s]+)\s2\sT")

find_regex(FIND_FASE12T, testo_fasi)

更多选项

FIND_FASE_PRIMA_123FRECCIAT = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*2([\w\s]+)\s*→\s*T")
    FIND_FASE_PRIMA_1FRECCIA23T = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)\s*(T|3\sT)")
    FIND_FASE_PRIMA_FRECCIA1F2FT = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)\s*→\s*(T|3\sT)")

find_regex(FIND_FASE_PRIMA_1FRECCIA23T, testo_fasi, FIND_FASE_PRIMA_123FRECCIAT, FIND_FASE_PRIMA_FRECCIA1F2FT)

我做错了什么?

【问题讨论】:

    标签: python regex python-3.x function


    【解决方案1】:

    你的逻辑错了:

    if opzione2 != None and opzione3 == None:
        # we get here only if opzione3 is None…
        matches_prima2 = re.findall(opzione2, x)
        lunghezza2 = len(matches_prima2)
        # …so there is no way opzione3 is not None HERE:
        if opzione2 != None and opzione3 != None:
            matches_prima3 = re.findall(opzione3, x)
    

    你可能想要这样的东西:

    def find_regex(regex, text, opzione2= None, opzione3 = None):
        lista = []
        for x in text:
            matches_prima = re.findall(regex, x)
            matches_prima2 = []
            matches_prima3 = []
            if opzione2 is not None:
                matches_prima2 = re.findall(opzione2, x)
                if opzione3 is not None:
                    matches_prima3 = re.findall(opzione3, x)
            lunghezza = len(matches_prima) + len(matches_prima2) + len(matches_prima3)
            lista.append(lunghezza)
        print("The number of {} matches is ".format(regex), sum(lista))
    

    【讨论】:

    • 谢谢!我看到有三个选项时有问题,可能是因为正则表达式第一个匹配不是列表而其他两个是?
    • 我的意思是它找不到三个选项
    • 我宁愿假设您将错误的正则表达式传递为 opzione3...
    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多