Python 3 - RegEx

Updated: 2018-06-27

Most Frequently Used: match, search and findall

  • re.match(): only match at the beginning of the string, returns a match object
  • locate a match anywhere in string, returns a match object
  • re.findall(): find all occurrences, returns a list of strings
>>> type("foo", "foobarfoo"))
<class '_sre.SRE_Match'>
>>> type(re.match("foo", "foobarfoo"))
<class '_sre.SRE_Match'>



re.match() and return a match object:

>>> match ="f(.*?),", "foo,faa,fuu,bar")
>>> match.groups()
('oo',) returns the string snippet that matches the pattern:


other group captures the ones in ():



re.findall() returns a list, extract value using []:

>>> match = re.findall("f(.*?),", "foo,faa,fuu,bar")
>>> match
['oo', 'aa', 'uu']
>>> match[0]

Compiled Patterns

pattern = re.compile(pattern_string)
result = pattern.match(string)

is equivalent to

result = re.match(pattern_string, string)

re.compile() returns a SRE_Pattern object:

>>> type(re.compile("pattern"))
<class '_sre.SRE_Pattern'>


dot matches everything except newlines