读书人

正则表达式为什么用了组后,不能获得正

发布时间: 2012-04-04 16:38:51 作者: rapoo

正则表达式为什么用了组后,不能获得正确的结果?

Python code
import rereg='a(b)'print re.findall(reg,'abc,1dabbcabds')#['b', 'b', 'b']p= re.match(reg,'abc,1dabbcabds')print p.group(0)#'ab'print p.group(1)#'b'print p.group(2)'''Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: no such group'''


以上不能获得三个'ab',只能获得三个'b'

[解决办法]
re.findall(pattern, string[, flags])¶

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

读书人网 >perl python

热点推荐