【正则表达式加括号就匹配不到】,该怎么处理
【正则表达式加括号就匹配不到】m re.findall([0-9]*4[0-9]*, [4])可以匹配到4m re.findall(([0-9]
【正则表达式加括号就匹配不到】
m = re.findall('[0-9]*4[0-9]*', '[4]')
可以匹配到4
m = re.findall('([0-9])*4([0-9])*', '[4]')
匹配不到4
请教大牛,这是为什么呢?PS,这个是一个简化的说明,我要用的正则比这个复杂,所以要用到(),表示一个序列的匹配。
补充一点,我放在notepad++中用的时候,两种写法都能匹配出来,不知道为什么python中就不行了。。
[解决办法]
如果是指匹配 4 的话:
>>> print re.findall('[0-9]', '[4]')
['4']
[解决办法]>>> print re.findall('([0-9])', '[4]')
['4']
[解决办法]看看文档先,有group的时候是不大一样...
re.findall(pattern, string, flags=0)
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.
[解决办法]
>>>m = re.findall('(([0-9])*4([0-9])*)', '[4]')
[('4', '', '')]
另外,我感觉你应该是
>>>m = re.findall('(([0-9]*)4([0-9]*))'), '[4]')
才对