Case insensitive regular expression without re.compile?
在python中,我可以使用
1 2 3 4 5 6 7 8 | >>> 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> |
有没有办法做到这一点,但不使用
将
1 2 3 | re.search('test', 'TeSt', re.IGNORECASE) re.match('test', 'TeSt', re.IGNORECASE) re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE) |
您还可以使用不带ignorecase标志的search/match执行不区分大小写的搜索(在python 2.7.3中测试):
1 2 | re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt' re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt' |
您还可以在模式编译期间定义不区分大小写:
1 | pattern = re.compile('FIle:/+(.*)', re.IGNORECASE) |
进口货物
1 | import re |
运行时处理:
1 2 | RE_TEST = r'test' if re.match(RE_TEST, 'TeSt', re.IGNORECASE): |
应该指出,不使用
应用内初始化:
1 | self.RE_TEST = re.compile('test', re.IGNORECASE) |
运行时处理:
1 | if self.RE_TEST.match('TeSt'): |
1 2 3 4 5 6 7 8 9 10 11 12 | #'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'> |