Extract Regex Match With Python Using Capture Groups

Pavol Kutaj
1 min readApr 28, 2021

--

The aim of this how-to guide🏁 is to show how a match can be extracted using regex in Python.

ESSENTIAL: replace match() with search() if the match is not in the beginning of the string.
> https://stackoverflow.com/a/180993/11082684

1. steps

  • so I need to extract 01 from the string 91.01 Demo B so here it goes
  1. import re module at the top of the script
  2. use re.compile() to create a regex object: reg = re.compile(<regex>)
  3. include a capture group for extraction purposes: reg = re.compile("\d{2}.(\d{2})")
  4. use match() on the created regex object to create a match object: s1 = reg.match(<string>)
  5. use group(<n>) on the created match object to access the first match
>>> import re
>>> reg = re.compile("\d{2}\.(\d{2})")u
>>> reg
re.compile('\\d{2}\\.(\\d{2})')
>>> s1 = reg.search("91.01 Demo B")
>>> s1
<re.Match object; span=(0, 5), match='91.01'>
>>> s1.group(1)
'01'
>>> type(s1)
<class 're.Match'>

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com