Why does re.findall () give me different results than re.finditer () in Python?

I wrote this regular expression:

p = re.compile(r'''
\[\[            #the first [[
[^:]*?          #no :s are allowed
.*?             #a bunch of chars
(
\|              #either go until a |
|\]\]           #or the last ]]
)
                ''', re.VERBOSE)

I want to use re.findallto get all the relevant sections of some string. I wrote some test codes, but it gives me fancy results.

This code

g = p.finditer('   [[Imae|Lol]]     [[sdfef]]')
print g
for elem in g:
    print elem.span()
    print elem.group()

gives me this result:

(3, 10)
[[Imae|
(20, 29)
[[sdfef]] 

Makes the right sense? But when I do this:

h = p.findall('   [[Imae|Lol]]     [[sdfef]]')
for elem in h:
    print elem

The conclusion is as follows:

|
]]  

Why doesn't findall () print the same results as finditer?

+5
source share
5 answers

Findall . , , , , . (?:...) - . :

'''
\[\[            #the first [[
[^:]*?          #no :s are allowed
.*?             #a bunch of chars
(?:             #non-capturing group
\|              #either go until a |
|\]\]           #or the last ]]
)
                '''
+7

re.findall() ( ) , , . , | ]] . , , re.finditer(), , .

re.findall(), , , - , . , -, " " 4. ,

p = re.compile(r'''
\[\[            #the first [[
[^:]*?          #no :s are allowed
(.*?)           #a bunch of chars
(
\|              #either go until a |
|\]\]           #or the last ]]
)
                ''', re.VERBOSE)

p.findall('   [[Imae|Lol]]     [[sdfef]]')

:

[('Imae', '|'), ('sdfef', ']]')]
+3

, findall() :

, ; , .

]] :

(
\|              #either go until a |
|\]\]           #or the last ]]
)

finditer(), , .

+1

. docs:

findall . , ; , .

finditer MatchObject.

+1

python:

, . , . , ; , . , .

Note that he says that if groups are present, then a list of group matches will be returned. The capture group that you have at the end of your regular expression matches, and therefore only the captured part of the groups in each match is returned. This information is just another field of the MatchObject when you use finditer.

0
source

All Articles