I IGNORECASE, 忽略大小写的匹配模式, 样例如下
s = 'hello World!' regex = re.compile("hello world!", re.I) print regex.match(s).group() #output> 'hello World!' #在正则表达式中指定模式以及注释 regex = re.compile("(?#注释)(?i)hello world!") print regex.match(s).group() #output> 'hello World!'
L LOCALE, 字符集本地化。这个功能是为了支持多语言版本的字符集使用环境的,比如在转义符\w,在英文环境下,它代表[a-zA-Z0-9_],即所以英文字符和数字。如果在一个法语环境下使用,缺省设置下,不能匹配"é" 或 "ç"。加上这L选项和就可以匹配了。不过这个对于中文环境似乎没有什么用,它仍然不能匹配中文字符。
M MULTILINE,多行模式, 改变 ^ 和 $ 的行为
s = '''first line second line third line''' # ^ regex_start = re.compile("^\w+") print regex_start.findall(s) # output> ['first'] regex_start_m = re.compile("^\w+", re.M) print regex_start_m.findall(s) # output> ['first', 'second', 'third'] #$ regex_end = re.compile("\w+$") print regex_end.findall(s) # output> ['line'] regex_end_m = re.compile("\w+$", re.M) print regex_end_m.findall(s) # output> ['line', 'line', 'line']
S DOTALL,此模式下 '.' 的匹配不受限制,可匹配任何字符,包括换行符
s = '''first line second line third line''' # regex = re.compile(".+") print regex.findall(s) # output> ['first line', 'second line', 'third line'] # re.S regex_dotall = re.compile(".+", re.S) print regex_dotall.findall(s) # output> ['first line\nsecond line\nthird line']
X VERBOSE,冗余模式, 此模式忽略正则表达式中的空白和#号的注释,例如写一个匹配邮箱的正则表达式
email_regex = re.compile("[\w+\.]+@[a-zA-Z\d]+\.(com|cn)") email_regex = re.compile("""[\w+\.]+ # 匹配@符前的部分 @ # @符 [a-zA-Z\d]+ # 邮箱类别 \.(com|cn) # 邮箱后缀 """, re.X)
U UNICODE,使用 \w, \W, \b, \B 这些元字符时将按照 UNICODE 定义的属性.
正则表达式的模式是可以同时使用多个的,在 python 里面使用按位或运算符 | 同时添加多个模式
如 re.compile('', re.I|re.M|re.S)
每个模式在 re 模块中其实就是不同的数字
print re.I # output> 2 print re.L # output> 4 print re.M # output> 8 print re.S # output> 16 print re.X # output> 64 print re.U # output> 32