Extract Regex Match With Python Using Capture Groups
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 string91.01 Demo B
so here it goes
import re
module at the top of the script- use
re.compile()
to create a regex object:reg = re.compile(<regex>)
- include a capture group for extraction purposes:
reg = re.compile("\d{2}.(\d{2})")
- use
match()
on the created regex object to create a match object:s1 = reg.match(<string>)
- 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'>