【问题标题】:Python Regex: capture all optional groups, regardless of orderPython Regex:捕获所有可选组,无论顺序如何
【发布时间】:2022-12-03 10:12:06
【问题描述】:

对于字符串“我有一只狗、一条鱼和一只猫”,我想按“狗”、“鱼”和“猫”的顺序捕获这些组。

我有一个按我想要的方式工作的 Python 正则表达式,使组成为可选的,以防字符串不包含组。所以“我有一只狗和一只猫”仍然会给我一组“狗”和“猫”。

^(?:.*(dog))?(?:.*(fish))?(?:.*(cat))?.*$

但是,无论正则表达式中组的顺序如何,我都想捕获这些组。如果字符串是“我有一条鱼、一条狗和一只猫”,当我仍然想要“狗”、“鱼”和“猫”时,我只会得到组“狗”和“猫”

我最初使用带有捕获组的前瞻来忽略顺序,但这只有在所有组都在字符串中时才有效。我试过将前瞻与非捕获组结合起来,但似乎无法正常工作。

任何帮助,将不胜感激!

这是我的正则表达式的链接:https://regex101.com/r/lhT55K/2

【问题讨论】:

    标签: regex regex-lookarounds regex-group


    【解决方案1】:

    试试这个代码:

    import re
    
    # The regular expression with named capture groups
    regex = r"(?P<dog>dog)?(?P<fish>fish)?(?P<cat>cat)?"
    
    # The string to match against
    string = "I have a dog, a fish, and a cat"
    
    # Use a lambda function to extract the groups in the order that you want
    match = re.match(regex, string, flags=re.IGNORECASE)
    groups = [match.groupdict()[g] for g in ["dog", "fish", "cat"]]
    
    # Print the groups
    print(groups)
    

    此代码应按 ["dog"、"fish"、"cat"] 的顺序打印组,而不管它们在字符串中出现的顺序如何。

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多