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 |
是否可以从
1 | p.pattern |
阅读此处有关重新模块的更多信息:http://docs.python.org/library/re.html网站
从
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及更高版本中的
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)上不起作用——
1 2 3 | >>> print dir(p) ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] |
。
对:
1 | print p.pattern |
号
提示:使用python中的
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'] |
。