在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.IGNORECASEflags 参数为 search, match, , 或者 sub:

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

其他提示

您也可以使用搜索/匹配,而不IGNORECASE标志(在Python 2.7.3测试)进行不区分大小写的搜索:

re.search(r'(?i)test', 'TeSt').group()    ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group()     ## returns 'TeSt'

在不区分大小写的标记,(?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)
#'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'>

在进口

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'):

要执行大小写不敏感的操作,供给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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top