Python正则表达式组

时间:2016-07-06 03:48:59

标签: python regex python-2.7

为什么此正则表达式打印('c',)()? 我想"([abc])+" === "([abc])([abc])([abc])..."

>>> import re
>>> m = re.match("([abc])+", "abc")
>>> print m.groups()
('c',)
>>> m.groups(0)
('c',)
>>> m = re.match("[abc]+", "abc")
>>> m.groups()
()
>>> m.groups(0)
()

2 个答案:

答案 0 :(得分:1)

有关 groups

的文档
  

返回一个包含匹配的所有子组的元组,从1到多个组都在模式中。默认参数用于未参与匹配的组;它默认为无。

在第一个正则表达式([abc])+中,它匹配字符abc,但只存储最后一个匹配

([abc])+
<----->
Matches a or b or c
Observe carefully. Capturing groups are surrounding only the character class
So, only one character from the matched character class can be stored in capturing group.

如果要在捕获组中捕获字符串abc,请使用

([abc]+)
  

上面会找到由abc组成的字符串,并将其存储在捕获组中。

在第二个正则表达式[abc]+中,没有捕获组,因此显示空结果。

答案 1 :(得分:0)

当您在括号后加上加号时,您一次匹配一个字符,多次。所以它匹配a然后b然后c,每次都覆盖前一个。移动+内部([abc] +)以匹配一个或多个。

相关问题