regex – Python extract pattern matches

regex – Python extract pattern matches

You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:

>>> p = re.compile(name (.*) is valid)
>>> result =
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>>     # group(1) will return the 1st capture (stuff within the brackets).
                        # group(0) will returned the entire matched text.

You can use matching groups:

p = re.compile(name (.*) is valid)


>>> import re
>>> p = re.compile(name (.*) is valid)
>>> s = 
... someline abc
... someother line
... name my_user_name is valid
... some more lines
>>> p.findall(s)

Here I use re.findall rather than to get all instances of my_user_name. Using, youd need to get the data from the group on the match object:

>>>   #gives a match object or None if no match is found
<_sre.SRE_Match object at 0xf5c60>
>>> #entire string that matched
name my_user_name is valid
>>> #first group that match in the string that matched

As mentioned in the comments, you might want to make your regex non-greedy:

p = re.compile(name (.*?) is valid)

to only pick up the stuff between name and the next is valid (rather than allowing your regex to pick up other is valid in your group.

regex – Python extract pattern matches

You could use something like this:

import re
s = #that big string
# the parenthesis create a group with what was matched
# and w matches only alphanumeric charactes
p = re.compile(name +(w+) +is valid, re.flags)
# use search(), so the match doesnt have to happen 
# at the beginning of big string
m =
# search() returns a Match object with information about what was matched
if m:
    name =
    raise Exception(name not found)

Leave a Reply

Your email address will not be published. Required fields are marked *