I need to check if a variable is a regular expression match object.
print(type(m))
returns something like that: <_sre.SRE_Match object at 0x000
You can do
SRE_MATCH_TYPE = type(re.match("", ""))
at the start of the program, and then
type(m) is SRE_MATCH_TYPE
each time you want to make the comparison.
Pile-on, since there's a whole bunch of ways to solve the problem:
def is_match_obj(m):
t = type(m)
return (t.__module__, t.__name__) == ('_sre', 'SRE_Match')
You can do something like this
isinstance(m, type(re.match("","")))
Usually there is no need to check the type of match objects, so noone has bothered to make a nice way to do it
from typing import Match
isinstance(m, Match)
As type(m)
returns a printable representation I would use:
repr(type(m)) == "<type '_sre.SRE_Match'>"
so you don't have to import the _sre
module and don't have to do any additional match
call.
That is for Python 2. It seems than in Python 3 the result of type(m) is different, something like <_sre.SRE_Match object at 0x000000000345BE68>
. If so I suppose you can use:
repr(type(m)).startswith("<_sre.SRE_Match")
or something similar (I don't have a Python 3 interpreter at hand right now, so this part of the answer can be inaccurate.).