check object being a compiled regular expression

Diez B. Roggisch deets at nospam.web.de
Sat Mar 25 18:12:20 CET 2006


Helmut Jarausch schrieb:
> Hi,
> sorry, this seems to be a FAQ but I couldn't find anything
> 
> I need to check if an object is a compiled regular expression
> 
> Say
> import re
> RX= re.compile('^something')
> 
> how to test
> 
> "if RX is a compiled regular expression"
> 
> type(RX)  says
> <type '_sre.SRE_Pattern'>
> 
> but
> 
> if isinstance(RX,_sre.SRE_Pattern)
> and
> if isinstance(RX,re._sre.SRE_Pattern)
> both fail.
> 
> Many thanks for a hint,


Just invoke type on a compiled expression and store that:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Welcome to rlcompleter2 0.96
for nice experiences hit <tab> multiple times
 >>> import re
 >>> re_type = type(re.compile("foo"))
 >>> isinstance(re.compile("bar"), re_type)
True
 >>>


Diez



More information about the Python-list mailing list