在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)的东西。
要执行不区分大小写的操作,请提供re.IGNORECASE
>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']
如果我们想替换匹配大小写的文本…
>>> def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'
#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string.
#'re.search' returns location of the where the match is found
#'re.compile' creates a regex object that can be used for multiple matches
>>> s = r'TeSt'
>>> print (re.match(s, r'test123', re.I))
<_sre.SRE_Match object; span=(0, 4), match='test'>
# OR
>>> pattern = re.compile(s, re.I)
>>> print(pattern.match(r'test123'))
<_sre.SRE_Match object; span=(0, 4), match='test'>