How can I get a pattern string from a compiled regex pattern in python

I have code like this:

>>> import re >>> p = re.compile('my pattern') >>> print p _sre.SRE_Pattern object at 0x02274380 

Is it possible to get the string "my pattern" from the variable p ?

+60
python regex
Sep 12 '09 at 19:34
source share
3 answers
 p.pattern 

Read more about the re-module here: http://docs.python.org/library/re.html

+69
Sep 12 '09 at 19:38
source share

From the "Regular Expression Objects" in the re module documentation:

RegexObject.pattern

The pattern string from which the RE object was compiled.

For example:

 >>> import re >>> p = re.compile('my pattern') >>> p <_sre.SRE_Pattern object at 0x1001ba818> >>> p.pattern 'my pattern' 

With the re module in Python 3.0 and above, you can find this by doing a simple dir(p) :

 >>> print(dir(p)) ['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'findall', 'finditer', 'flags', 'groupindex', 'groups', 'match', 'pattern', 'scanner', 'search', 'split', 'sub', 'subn'] 

However, this does not work on Python 2.6 (or 2.5) - the dir command is not perfect, so it’s always worth checking out the documents!

 >>> print dir(p) ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] 
+17
Sep 12 '09 at 19:59
source share

Yes:

 print p.pattern 

use the dir function in python to get a list of members:

 dir(p) 

in this list:

 ['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'findall', 'finditer', 'flags', 'groupindex', 'groups', 'match', 'pattern', 'scanner', 'search', 'split', 'sub', 'subn'] 
+6
Sep 12 '09 at 19:39
source share



All Articles