gpt4 book ai didi

python - 如何使用 re 模块提取匹配的模式

转载 作者:行者123 更新时间:2023-12-01 05:38:08 25 4
gpt4 key购买 nike

当我执行以下程序时几乎没有修改,但出现错误。

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

最佳答案

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

m = match.search(line)

然后:

m.group()

关于python - 如何使用 re 模块提取匹配的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18379667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com