Type of compiled regex object in python

后端 未结 10 977
一个人的身影
一个人的身影 2020-11-30 07:14

What is the type of the compiled regular expression in python?

In particular, I want to evaluate

isinstance(re.compile(\'\'), ???)

相关标签:
10条回答
  • 2020-11-30 07:54

    When the type of something isn't well specified, there's nothing wrong with using the type builtin to discover the answer at runtime:

    >>> import re
    >>> retype = type(re.compile('hello, world'))
    >>> isinstance(re.compile('goodbye'), retype)
    True
    >>> isinstance(12, retype)
    False
    >>> 
    

    Discovering the type at runtime protects you from having to access private attributes and against future changes to the return type. There's nothing inelegant about using type here, though there may be something inelegant about wanting to know the type at all.

    0 讨论(0)
  • 2020-11-30 07:55

    FYI an example of such code is in BeautifulSoup: http://www.crummy.com/software/BeautifulSoup and uses the 'hasattr' technique. In the spirit of the "alternative approach", you might also encapsulate your string search in a regexp by doing this: regexp = re.compile(re.escape(your_string)) therefore having a list of only regular expressions.

    0 讨论(0)
  • 2020-11-30 07:58

    It is possible to compare a compiled regular expression with 're._pattern_type'

    import re
    pattern = r'aa'
    compiled_re = re.compile(pattern)
    print isinstance(compiled_re, re._pattern_type)
    
    >>True
    

    Gives True, at least in version 2.7

    0 讨论(0)
  • 2020-11-30 08:00
    >>> import re
    >>> regex = re.compile('foo')
    >>> regex
    <_sre.SRE_Pattern object at 0x10035d960>
    

    Well - _sre is a C extension doing the pattern matching...you may look in the _sre C source.

    Why do you care?

    Or you try something like this (for whatever reason - I don't care):

    >>> regex1 = re.compile('bar')
    >>> regex2 = re.compile('foo')
    >>> type(regex1) == type(regex2)
    True
    
    0 讨论(0)
提交回复
热议问题