在Python中,我可以使用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>

是否有一种方法可以做同样的事情,但不使用re.compile。我在文档中找不到任何类似Perl的I后缀(例如m/test/ I)的东西。


当前回答

对于不区分大小写的正则表达式: 在代码中添加有两种方法:

旗帜=再保险。IGNORECASE Regx3GList = re.search(“(WCDMA) ((\ d *)(,?))*", txt re.IGNORECASE) 不区分大小写的标记(?i) Regx3GList = re.search(“* *(?我)* * (WCDMA:) ((\ d *)(,?))*", txt)

其他回答

将re.IGNORECASE传递给search、match或sub的flags参数:

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

不区分大小写的标记(?i)可以直接合并到正则表达式模式中:

>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']

你也可以在模式编译时定义不区分大小写:

pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)

对于不区分大小写的正则表达式: 在代码中添加有两种方法:

旗帜=再保险。IGNORECASE Regx3GList = re.search(“(WCDMA) ((\ d *)(,?))*", txt re.IGNORECASE) 不区分大小写的标记(?i) Regx3GList = re.search(“* *(?我)* * (WCDMA:) ((\ d *)(,?))*", txt)

进口

import re

在运行时处理中:

RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):

应该提到的是,不使用re.compile是一种浪费。每次调用上述匹配方法时,正则表达式都将被编译。这在其他编程语言中也是错误的做法。下面是更好的实践。

在应用程序初始化中:

self.RE_TEST = re.compile('test', re.IGNORECASE)

在运行时处理中:

if self.RE_TEST.match('TeSt'):