f



check object being a compiled regular expression

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,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
0
jarausch (168)
3/25/2006 3:58:09 PM
comp.lang.python 77058 articles. 6 followers. Post Follow

2 Replies
464 Views

Similar Articles

[PageSpeed] 55

This is crude, but works:

>>> import re
>>> RX= re.compile('^something')
>>> str(RX).find("<_sre.SRE_Pattern") == 0
True

0
3/25/2006 5:01:11 PM
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
0
deets (3351)
3/25/2006 5:12:20 PM
Reply: