关于正则表达式:如何在python中从已编译的正则表达式模式中获取模式字符串

how can i obtain pattern string from compiled regexp pattern in python

我有这样的代码:

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

是否可以从p变量中获取字符串"my pattern"


1
p.pattern

阅读此处有关重新模块的更多信息:http://docs.python.org/library/re.html网站


re模块文档的"正则表达式对象"部分:

RegexObject.pattern

The pattern string from which the RE object was compiled.

例如:

1
2
3
4
5
6
>>> import re
>>> p = re.compile('my pattern')
>>> p
<_sre.SRE_Pattern object at 0x1001ba818>
>>> p.pattern
'my pattern'

使用python 3.0及更高版本中的re模块,您可以通过执行一个简单的dir(p)来找到这一点:

1
2
3
4
5
6
7
8
>>> 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']

然而,这在python 2.6(或2.5)上不起作用——dir命令并不完美,所以总是值得检查文档!

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


对:

1
print p.pattern

提示:使用python中的dir函数获取成员列表:

1
dir(p)

此列表:

1
2
3
4
5
6
['__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']