虽然我执行了以下程序而几乎没有修改,但我收到了错误。
import sys,re
match=re.compile(r'aa[0-9]+AB')
while 1 :
line=eval(raw_input('Enter the string to search' 'or' "press 'q' to Quit"))
if line == 'q':
print "you are quit from the program"
break
if match.search(line):
print 'Matched:',line
print pat
print 'found',match.group()
print type(pat)
else:
print "no match"
print type(pat)
输入:
'aa12AB'
O / P:
>>> Matched: aa12AB
<_sre.SRE_Pattern object at 0x02793720>
found
Traceback (most recent call last):
File "C:\Pyth`enter code here`on27\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\thangaraj\Desktop\python program\UK Training program\New to add labtop\regular exp\Script1.py", line 11, in <module>
print 'found',match.group()
AttributeError: '_sre.SRE_Pattern' object has no attribute 'group'
>>>
答案 0 :(得分:1)
您必须分配到match
对象:
m = match.search(line)
然后:
m.group()
答案 1 :(得分:1)
您为什么使用eval
?您应该使用match.search
(尽管您应该通常将match
重命名为变量,search
的返回值称为匹配),search
的返回值将有一个group
方法,正如@Birei写的那样。