我认为 pat1 = '[ab]' 和 pat2 = 'a|b' 在 Python(python2.7, windows) 're' 模块中作为正则表达式模式具有相同的功能。但是我对'[ab]+'和'(a|b)+'感到困惑,它们是否具有相同的功能,如果没有,你能解释一下细节。
'''
Created on 2012-9-4
@author: melo
'''
import re
pat1 = '(a|b)+'
pat2 = '[ab]+'
text = '22ababbbaa33aaa44b55bb66abaa77babab88'
m1 = re.search(pat1, text)
m2 = re.search(pat2, text)
print 'search with pat1:', m1.group()
print 'search with pat2:', m2.group()
m11 = re.split(pat1, text)
m22 = re.split(pat2, text)
print 'split with pat1:', m11
print 'split with pat2:', m22
m111 = re.findall(pat1, text)
m222 = re.findall(pat2, text)
print 'findall with pat1:', m111
print 'findall with pat2:', m222
输出如下:
search with pat1: ababbbaa
search with pat2: ababbbaa
split with pat1: ['22', 'a', '33', 'a', '44', 'b', '55', 'b', '66', 'a', '77', 'b', '88']
split with pat2: ['22', '33', '44', '55', '66', '77', '88']
findall with pat1: ['a', 'a', 'b', 'b', 'a', 'b']
findall with pat2: ['ababbbaa', 'aaa', 'b', 'bb', 'abaa', 'babab']
为什么'pat1'和'pat2'不同,它们有什么区别?'pat1' 实际上可以匹配什么样的字符串?