Skip to content
Advertisement

Get the part of the string matched by regex

In the case of re.search(), is there a way I can get hold of just the part of input string that matches the regex? i.e. I just want the "heeehe" part and not the stuff that comes before it:

>>> s = "i got away with it, heeehe"
>>> import re
>>> match = re.search("he*he", s)
>>> match.string
'i got away with it, heeehe'
>>> match.?
'heeehe'

Advertisement

Answer

match.group(0) is the matched string.

Demo:

>>> import re
>>> s = "i got away with it, heeehe"
>>> match = re.search("he*he", s)
>>> match.group(0)
'heeehe'

You can also omit the argument, 0 is the default.

Advertisement