使用re.IGNORECASE或re.I标志可实现不区分大小写的正则匹配,如re.findall(r'python', text, re.I)能匹配'Python'、'python'和'PYTHON'。

在Python中使用正则表达式时,若要实现不区分大小写匹配,可以通过设置标志参数 re.IGNORECASE 或简写为 re.I 来实现。
使用 re.IGNORECASE 标志
在调用 re 模块的方法时,传入 re.IGNORECASE 参数即可让匹配忽略大小写:import re <p>text = "Python is great. I love python. PYTHON rocks!" matches = re.findall(r'python', text, re.IGNORECASE) print(matches) # 输出: ['Python', 'python', 'PYTHON']</p>
使用 re.I(简写形式)
re.I 是 re.IGNORECASE 的简写,功能完全相同:matches = re.findall(r'python', text, re.I) print(matches) # 同样输出: ['Python', 'python', 'PYTHON']
在编译正则表达式时使用
如果使用 re.compile() 预编译正则表达式,也可以将标志传入:pattern = re.compile(r'python', re.IGNORECASE) matches = pattern.findall(text) print(matches) # 输出: ['Python', 'python', 'PYTHON']
在多行或复杂匹配中同样有效
该标志可与其他标志组合使用,比如与 re.MULTILINE 或 re.DOTALL 一起:text = """Python pyTHON PYTHON""" matches = re.findall(r'^python$', text, re.IGNORECASE | re.MULTILINE) print(matches) # 匹配每一行的 "python"(不区分大小写)
基本上就这些。只要加上 re.IGNORECASE 或 re.I,就能轻松实现不区分大小写的正则匹配。











