Check if a variable is SRE_Match

前端 未结 5 1723
自闭症患者
自闭症患者 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 02:47

    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.

    0 讨论(0)
  • 2021-01-19 02:53

    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')
    
    0 讨论(0)
  • 2021-01-19 02:57

    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

    0 讨论(0)
  • 2021-01-19 02:59
    from typing import Match
    
    isinstance(m, Match)
    
    0 讨论(0)
  • 2021-01-19 03:11

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

    0 讨论(0)
提交回复
热议问题