【问题标题】:Python Regular Expression re.finditer 2 matchesPython 正则表达式 re.finditer 2 匹配
【发布时间】:2020-03-26 07:49:31
【问题描述】:

我希望使用单个函数来匹配可以在另一个函数中使用的多个值。

我可以在下面使用单个正则表达式值,寻找与第二个正则表达式“regex2”匹配的建议

工作---

def parse_desc(description):
    regex = r"^Created on\((.*?)\) for (.*?) "
    matches = re.finditer(regex, description, re.MULTILINE)
    for matchNum, match in enumerate(matches):
        return match.groups()
    return '', ''

建议 --- 尝试查找“创建于”和“复制于”的匹配项

def pass_desc(description):
    regex = r"^Created on\((.*?)\) for (.*?) "
    regex2 = r"^(.*?)Copied on (.*?) "
    matches = re.finditer(regex, description, re.MULTILINE) or re.finditer(regex2, description, re.MULTILINE)
    for matchNum, match in enumerate(matches):
        return match.groups()
    return '', ''

我可以让两个正则表达式作为单个函数工作

【问题讨论】:

  • 编写一个新的正则表达式,将两者与| 结合起来

标签: python regex python-3.x python-2.7


【解决方案1】:
def pass_desc(description):
    regex = r"^Created on\((.*?)\) for (.*?) "
    regex2 = r"^(.*?)Copied on (.*?) "
    matches = re.finditer(regex, description, re.MULTILINE)
    matches2 = re.finditer(regex2, description, re.MULTILINE)

    from itertools import chain
    y_iter = chain(matches, matches2)

    for matchNum, match in enumerate(y_iter):
        return match.groups()
    return '', ''

【讨论】:

    【解决方案2】:

    将两个正则表达式与|(或)结合起来。现在每场比赛将返回 4 个组,其中两个将是None,具体取决于匹配的内容。即使您有一个for 循环,但您在检索到第一个匹配项后发出了一个return,这是不正确的。更新后的代码,它使用 list comprehension 返回 all 匹配项:

    重新导入

    def pass_desc(description):
        regex12 = r"^Created on\((.*?)\) for (.*?) |^(.*?)Copied on (.*?) "
        return [match.groups() for match in re.finditer(regex12, description, re.MULTILINE)]
    
    print(pass_desc('Created on(Tuesday) for Mary \nIt was Copied on Friday for Sally.'))
    

    打印:

    [('Tuesday', 'Mary', None, None), (None, None, 'It was ', 'Friday')]
    

    【讨论】:

    • 尝试此功能时出现错误。 “ValueError:没有足够的值来解包(预期 2,得到 1)”@Booboo
    • 导致错误的输入文本是什么,具体是哪一行代码引发了错误?
    • 能够使用 from itertools import chain y_iter = chain(l1, l2)
    【解决方案3】:

    要查看为什么这种方法不起作用,请尝试在解释器中执行 1 or 2。此行为在here 进行了解释。

    我会分别搜索这两种模式,然后在随后的两个for 循环中遍历它们。如果您需要一个迭代器对象,应该可以使用

    from itertools import chain
    y_iter = chain(l1, l2)
    

    将两个迭代器对象链接在一起。

    【讨论】:

    • 所以在我的情况下 y_iter = chain(regex, regex2) ,然后我可以调用 y_iter。试图弄清楚如何与上述单个功能相关。
    • def parse_description(description): regex = r"^Created on((.*?)) for (.*?) " regex2 = r"^(.*?)Copyed on (.* ?) " 匹配 = re.finditer(regex, description, re.MULTILINE) matches2 = re.finditer(regex2, description, re.MULTILINE) for matchNum, 匹配枚举(matches): return match.groups() return '' , '' for matchNum, match in enumerate(matches2): return match.groups() return '', ''
    • 感谢您的评论和链接stackoverflow.com/questions/44116557/…
    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 2013-09-22
    • 2022-12-11
    • 2011-06-07
    • 2015-09-14
    • 2021-12-31
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多