Skip to content
Find All Matches
step 1/5

Reading — step 1 of 5

Read

~1 min readProduction Features

Find All Matches

re.findall() and re.finditer() walk the string returning every non-overlapping match.

python

Algorithm:

python

The max(m.end, i + 1) guard is important: if your pattern is .*, every position matches with length 0, so without the guard you'd loop forever.

re.split(pattern, text) is the inverse: cut the text at every match, return the pieces:

python

re.sub(pattern, repl, text) does findall + replace in one pass. Replacement strings can use \1, \2 to reference captures.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…