Expressão regular case insensitive sem re.compile?
-
20-08-2019 - |
Pergunta
Em Python, posso compilar uma expressão regular para ser maiúsculas e minúsculas usando 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>
Existe uma maneira de fazer o mesmo, mas sem usar re.compile
. Não consigo encontrar qualquer coisa como sufixo i
do Perl (por exemplo m/test/i
) na documentação.
Outras dicas
Você também pode executar casos pesquisas minúsculas usando pesquisa / partida sem a bandeira ignoreCase (testado em Python 2.7.3):
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
O marcador de maiúsculas e minúsculas, (?i)
pode ser incorporado directamente no padrão de expressão regular:
>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']
Você também pode definir maiúsculas e minúsculas durante a compilação padrão:
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'>
Nas importações
import re
No processamento de tempo de execução:
RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):
Deve ser mencionado que não usar re.compile
é um desperdício. Cada vez que o método de jogo acima é chamado, a expressão regular será compilado. Esta é também a prática defeituosa em outras linguagens de programação. A seguir é a melhor prática.
Na inicialização app:
self.RE_TEST = re.compile('test', re.IGNORECASE)
No processamento de tempo de execução:
if self.RE_TEST.match('TeSt'):
Para executar operações maiúsculas e minúsculas, fornecer re.IGNORECASE
>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']
e se queremos substituir o texto correspondente ao caso ...
>>> 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'