tags:

views:

137

answers:

4

I have some code like this one:

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

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

+5  A: 

Why not to read docs before posting such questions?

p.pattern

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

Mihail
Thanks. I don't read docs becouse i try i dir(p) and it display only several attributes and methods. http://stackoverflow.com/questions/1415924/how-can-i-obtain-pattern-string-from-compiled-regexp-pattern-in-python/1415943#1415943
Mykola Kharechko
+1  A: 

Yes:

print p.pattern

hint, use the dir function in python to obtain a list of members:

dir(p)

this lists:

['__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']
Lasse V. Karlsen
`help( value )` is much more useful on the console.
THC4k
A: 

Thanks. p.pattern really works. But my dir don't display this attribute


>>> sys.version
'2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)]'
>>> dir(p)
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
>>> p.pattern
'my pattern'
>>>
>>> dir
built-in function dir

Mykola Kharechko
`dir(p)` only contains `pattern` on Python 3.0 and above, it doesn't work in 2.5, 2.6 etc
dbr
+1  A: 

From the "Regular Expression Objects" section of 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']

This however does not work on Python 2.6 (or 2.5) - the dir command isn't perfect, so it's always worth checking the docs!

>>> print dir(p)
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner',
'search', 'split', 'sub', 'subn']
dbr