有时候需要匹配一组特殊需求的字符,可以使用 [ ] 定义。
例如:
① 字符 [aeiouAEIOU] 将匹配所有的元音字符,包括大小写
>>> import re
>>> testReg = re.compile(r'[aeiouAEIOU]')
>>> test = testReg.findall('A test message !')
>>> test
['A', 'e', 'e', 'a', 'e']
>>>
② 字符 [a-zA-Z0-9] 将匹配所有字母(包括大、小写)、数字
>>> import re
>>> testReg = re.compile(r'[a-zA-Z0-9]')
>>> test = testReg.findall('A test message for 123 .\=-;./%$##%$^^DFDDG')
>>> test
['A', 't', 'e', 's', 't', 'm', 'e', 's', 's', 'a', 'g', 'e', 'f', 'o', 'r', '1', '2', '3', 'D', 'F', 'D', 'D', 'G']
>>>
③ 方括号内 不需要使用转义字符
# 使用转义字符
>>> import re
>>> testReg = re.compile(r'[test\.]')
>>> test = testReg.findall('A test message for 123 .\=-;./%$##%$^^DFDDG')
>>> test
['t', 'e', 's', 't', 'e', 's', 's', 'e', '.', '.']
# 不使用转义字符,可以看到结果一样
>>> testReg2 = re.compile(r'[test.]')
>>> test2 = testReg2.findall('A test message for 123 .\=-;./%$##%$^^DFDDG')
>>> test2
['t', 'e', 's', 't', 'e', 's', 's', 'e', '.', '.']
>>>
④ 使用 ^ 可以匹配不在字符类中的所有字符。例如:
[^aeiouAEIOU] 将匹配所有元音字符以外的字符
>>> import re
>>> testReg = re.compile(r'[^aeiouAEIOU]')
>>> test = testReg.findall('A test message for 123 .\=-;./%$##%$^^DFDDG')
>>> test
[' ', 't', 's', 't', ' ', 'm', 's', 's', 'g', ' ', 'f', 'r', ' ', '1', '2', '3', ' ', '.', '\\', '=', '-', ';', '.', '/', '%', '$', '#', '#', '%', '$', '^', '^', 'D', 'F', 'D', 'D', 'G']
>>>