不重新编译的不区分大小写的正则表达式? [英] Case insensitive regular expression without re.compile?
本文介绍了不重新编译的不区分大小写的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,我可以使用 re.compile
将正则表达式编译为不区分大小写:
有没有办法做同样的事情,但不使用re.compile
.我在文档中找不到任何类似于 Perl 的 i
后缀(例如 m/test/i
).
解决方案
将 re.IGNORECASE
传递给 search
, match
或 sub
:
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屋!
查看全文