【问题标题】:Python regex groupDict with repetitions of groupsPython 正则表达式 groupDict 与组的重复
【发布时间】:2021-12-28 20:11:51
【问题描述】:

想知道是否有像match.groupdict() 这样的函数可以捕获类似于match.captures 函数的重复。

当我运行这段代码时:

import regex

test = regex.compile("(?P<a>a)*(?P<b>b)*(?P<c>c)*")
test.match("aabbbcc").groupdict()

我明白了:

{'a': 'a', 'b': 'b', 'c': 'c'}

我想要的是这样的:

{'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c', 'c']}

是否有这样做的功能,还是我应该自己手动完成?

【问题讨论】:

    标签: python regex regex-group python-regex


    【解决方案1】:

    你可以使用

    import regex
    test=regex.compile("(?P<a>a)*(?P<b>b)*(?P<c>c)*")
    print ( test.match("aabbbcc").capturesdict() )
    # => {'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c', 'c']}
    

    或者,如果您需要将整个字符串与此模式匹配,请将.match 替换为.fullmatch

    test.fullmatch("aabbbcc").capturesdict()
    

    请参阅Python demo

    PyPi regex module documentation

    capturesdict 返回命名组的字典和这些组的所有捕获的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      相关资源
      最近更新 更多