1 # 列表([])和 择一匹配符(|)完成相同的效果 2 import re 3 4 m = re.match('[xzy]','x') 5 print(m.group()) 6 m = re.match('x|y|z','x') 7 print(m.group()) 8 9 # 字符集列表与择一匹配符的用法,及差异 10 pattern = r'[ab][cd]' 11 # 匹配第一个字母是a或b,第一个字母是c或d 12 s = 'ac' 13 # <re.Match object; span=(0, 2), match='ac'> 14 s = 'ab' 15 # None 16 m = re.match(pattern,s) 17 print(m) 18 19 pattern = r'ab[cd]' 20 # 以ab开头,后面以c或d开头 21 s = 'ab' # None 22 s = 'abc' 23 # <re.Match object; span=(0, 3), match='abc'> 24 s = 'abd' 25 # <re.Match object; span=(0, 3), match='abd'> 26 m = re.match(pattern,s) 27 print(m) 28 29 pattern = 'ab|cd' 30 s = 'abc' 31 # <re.Match object; span=(0, 2), match='ab'> 32 s = 'abd' 33 # <re.Match object; span=(0, 2), match='ab'> 34 s = 'cd' 35 # <re.Match object; span=(0, 2), match='cd'> 36 m = re.match(pattern,s) 37 print(m)