Python re.findall() is not working as expected

前端 未结 4 1719
清酒与你
清酒与你 2020-12-06 16:45

I have the code:

import re
sequence=\"aabbaa\"
rexp=re.compile(\"(aa|bb)+\")
rexp.findall(sequence)

This returns [\'aa\']

4条回答
  •  没有蜡笔的小新
    2020-12-06 17:30

    your pattern

    rexp=re.compile("(aa|bb)+")
    

    matches the whole string aabbaa. to clarify just look at this

    >>> re.match(re.compile("(aa|bb)+"),"aabbaa").group(0)
    'aabbaa'
    

    Also no other substrings are to match then

    >>> re.match(re.compile("(aa|bb)+"),"aabbaa").group(1)
    'aa'
    

    so a findall will return the one substring only

    >>> re.findall(re.compile("(aa|bb)+"),"aabbaa")
    ['aa']
    >>> 
    

提交回复
热议问题