1

当我几乎没有修改执行以下程序时,我收到了一个错误。

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'

输出/输出:

>>>  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'
>>> 
4

2 回答 2

1

你为什么用eval?您应该使用match.search(尽管您可能应该像往常一样重命名变量match,返回值search称为匹配)并且返回值search将有一个group方法,正如@Birei 所写。

于 2013-08-22T12:04:24.267 回答
1

您必须分配给一个match对象:

m = match.search(line)

接着:

m.group()
于 2013-08-22T11:58:16.153 回答