import re
pattern = re.compile(r'apple', flags=re.IGNORECASE)
result = pattern.match('Apple')print(result.group())# 输出: 'Apple'
re.MULTILINE 或 re.M
多行匹配,影响 ^ 和 $,使它们匹配字符串的每一行的开头和结尾。
import re
pattern = re.compile(r'^\d+', flags=re.MULTILINE)
text ='123\n456\n789'
result = pattern.findall(text)print(result)# 输出: ['123', '456', '789']
re.DOTALL 或 re.S:
使 . 匹配包括换行符在内的任意字符。
import re
pattern = re.compile(r'a.b', flags=re.DOTALL)
result = pattern.match('a\nb')print(result.group())# 输出: 'a\nb'
re.ASCII
使 \w, \W, \b, \B, \d, \D, \s, \S 仅匹配 ASCII 字符。
import re
pattern = re.compile(r'\w+', flags=re.ASCII)
result = pattern.match('Hello123')print(result.group())# 输出: 'Hello123'
re.VERBOSE 或 re.X
忽略空格和注释,可以更清晰地组织复杂的正则表达式。
import re
pattern = re.compile(r'''
\d+ # 匹配数字
[a-z]+ # 匹配小写字母
''', flags=re.VERBOSE)
result = pattern.match('123abc')print(result.group())# 输出: '123abc'