Capturing named groups in regex with re.findall

后端 未结 3 1248
忘了有多久
忘了有多久 2021-01-02 20:28

When I was trying to answer this question: regex to split %ages and values in python I noticed that I had to re-order the groups from the result of findall. For example:

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 20:35

    Take 3, based on a further clarification of the OP's intent in this comment.

    Ashwin is correct that findall does not preserve named capture groups (e.g. (?Pregex)). finditer to the rescue! It returns the individual match objects one-by-one. Simple example:

    data = """34% passed 23% failed 46% deferred"""
    for m in re.finditer('(?P\w+)%\s(?P\w+)', data):
        print( m.group('percentage'), m.group('word') )
    

提交回复
热议问题