不重新编译的不区分大小写的正则表达式? [英] Case insensitive regular expression without re.compile?

查看:20
本文介绍了不重新编译的不区分大小写的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我可以使用 re.compile 将正则表达式编译为不区分大小写:

<预><代码>>>>s = '测试'>>>casesensitive = re.compile('test')>>>ignorecase = re.compile('test', re.IGNORECASE)>>>>>>打印 casesensitive.match(s)没有任何>>>打印 ignorecase.match(s)<_sre.SRE_Match 对象在 0x02F0B608>

有没有办法做同样的事情,但不使用re.compile.我在文档中找不到任何类似于 Perl 的 i 后缀(例如 m/test/i).

解决方案

re.IGNORECASE 传递给 search, matchsub:

re.search('test', 'TeSt', re.IGNORECASE)re.match('test', 'Test', re.IGNORECASE)re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

In Python, I can compile a regular expression to be case-insensitive using re.compile:

>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>> 
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>

Is there a way to do the same, but without using re.compile. I can't find anything like Perl's i suffix (e.g. m/test/i) in the documentation.

解决方案

Pass re.IGNORECASE to the flags param of search, match, or sub:

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

这篇关于不重新编译的不区分大小写的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆