gpt4 book ai didi

Python 不允许我用正则表达式做 match.group()?

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:38 25 4
gpt4 key购买 nike

我用 Python 编写了一个正则表达式来从字符串中获取数字。但是,当我运行 match.group() 时,它说对象 list 没有属性 group。我究竟做错了什么?我输入的代码粘贴到终端,以及终端的响应。谢谢。

>>> #import regex library
... import re
>>>
>>> #use a regex to just get the numbers -- not the rest of the string
... matcht = re.findall(r'\d', dwtunl)
>>> matchb = re.findall(r'\d', ambaas)
>>> #macht = re.search(r'\d\d', dwtunl)
...
>>> #just a test to see about my regex
... print matcht.group()
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AttributeError: 'list' object has no attribute 'group'
>>> print matchb.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'group'
>>>
>>> #start defining the final variables
... if dwtunl == "No Delay":
... dwtunnl = 10
... else:
... dwtunnl = matcht.group()
...
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
AttributeError: 'list' object has no attribute 'group'
>>> if ambaas == "No Delay":
... ammbaas = 10
... else:
... ammbaas = matchb.group()
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AttributeError: 'list' object has no attribute 'group'

最佳答案

re.findall() 不返回匹配对象(或它们的列表),它总是返回字符串列表(或字符串元组列表,如果是有不止一个捕获组)。并且列表没有 .group() 方法。

>>> import re
>>> regex = re.compile(r"(\w)(\W)")
>>> regex.findall("A/1$5&")
[('A', '/'), ('1', '$'), ('5', '&')]

re.finditer() 将返回一个迭代器,每次匹配产生一个匹配对象。

>>> for match in regex.finditer("A/1$5&"):
... print match.group(1), match.group(2)
...
A /
1 $
5 &

关于Python 不允许我用正则表达式做 match.group()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19637710/

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