1

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

3 回答 3

4

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 &
于 2013-10-28T14:43:41.710 回答
0

因为re.findall(r'\d', ambaas)返回一个list. 您可以遍历列表,例如:

for i in stored_list

或者只是stored_list[0]

于 2013-10-28T14:43:59.090 回答
0

re.findall()返回字符串列表,而不是match对象。你可能的意思是re.finditer

于 2013-10-28T14:45:21.670 回答