Teddy Bo
Teddy Bo

Reputation: 679

Check if a variable is SRE_Match

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 0x000000000345BE68>

but when I import _sre and try to execute type(m) is SRE_Match the exception NameError: name 'SRE_Match' is not defined is raised.

Upvotes: 6

Views: 3199

Answers (5)

Fedor
Fedor

Reputation: 76

from typing import Match

isinstance(m, Match)

Upvotes: 1

Vicent
Vicent

Reputation: 5452

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.).

Upvotes: 0

nneonneo
nneonneo

Reputation: 179687

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')

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304413

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

Upvotes: 0

David Robinson
David Robinson

Reputation: 78620

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.

Upvotes: 7

Related Questions