如何获得类似于" findall"在python的re模块中命令?

时间:2015-10-11 16:48:14

标签: python regex python-2.7

正如我们所知,"搜索"命令返回一个匹配对象。

mystring= 'string with numbers 990'
my_obj = re.search('(.{1}[h0])',mystring)

我希望能够打印匹配字符串列表,类似于findall方法。我尝试my_obj.groups(),但这仍然只打印第一个匹配的对象:

findall_result = re.findall('(.{1}[h0])',mystring)

>>> findall_result
['th', '90']
>>> my_obj.groups()
('th',)
>>> 

如何从匹配对象(如findall)返回所有匹配的字符串?

2 个答案:

答案 0 :(得分:2)

You could use mo.group(), not groups. mo.group(1) with refer
 to the first bracketed group and so on. but mo.group(0) to 
 the whole string match.

s = "somethingabcdeabcdeabcdeabcdeabcdeelseabcdeabcdeabcde"

mo = re.search(r"(abc)d(ea)", s)

print(mo.group(0))
#abcdea
print(mo.group(1))
# abc
print(mo.group(2))
# ea

 mystring= 'string with numbers 990'

mo = re.search(r'(\wg\s).*\s(\d\d)\d',mystring)

print(mo.group(0))
# ng with numbers 990
print(mo.group(1))
# ng
print(mo.group(2))
# 99

答案 1 :(得分:2)

您可以使用finditer

print [m.group(0) for m in re.finditer('(.{1}[h0])',mystring)]