在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)的东西。


当前回答

如果你想替换但仍然保持前str的风格,这是可能的。

例如:突出显示字符串“test asdasd test asd test asdasd”。

sentence = "test asdasd TEST asd tEst asdasd"
result = re.sub(
  '(test)', 
  r'<b>\1</b>',  # \1 here indicates first matching group.
  sentence, 
  flags=re.IGNORECASE)

test asdasd测试asdasd

其他回答

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

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

将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)用以下有效标志匹配模式的剩余部分:不区分大小写匹配(忽略[a-zA-Z]的大小写)

>>> import pandas as pd
>>> s = pd.DataFrame({ 'a': ["TeSt"] })
>>> r = s.replace(to_replace=r'(?i)test', value=r'TEST', regex=True)
>>> print(r)
      a
0  TEST

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

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

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

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