说说 Python 正则表达式中,如何实现不区分大小写

默认, 正则表达式是依赖于模式的字符串大小写来严格匹配文本的。

sound_regex=re.compile(r'sound')
result=sound_regex.search('Sounds like you may be far-sighted.')
print(result==None)

运行结果:

True

我们可以向 re.compile()传入 re.IGNORECASE 或 re.I,作为第二个参数,让正则表达式以不区分大小写的形式,来匹配文本。

sound_regex=re.compile(r'sound', re.I)
result=sound_regex.search('Sounds like you may be far-sighted.')
print(result.group())

运行结果:

Sound


英语在编程世界有天然的优势。

发布了601 篇原创文章 · 获赞 668 · 访问量 88万+

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/103791588