正则表达式为什么用了组后,不能获得正确的结果?该如何解决
正则表达式为什么用了组后,不能获得正确的结果?Python codeimport rerega(b)print re.findall(reg,abc
正则表达式为什么用了组后,不能获得正确的结果?
Python codeimport 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.