Check if a variable is SRE_Match

前端 未结 5 1724
自闭症患者
自闭症患者 2021-01-19 02:30

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

5条回答
  •  无人及你
    2021-01-19 03:11

    As type(m) returns a printable representation I would use:

    repr(type(m)) == ""
    

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

提交回复
热议问题