Extract Regex Match With Python Using Capture Groups

1. steps

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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj


Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com