¿Expresión regular sin distinción entre mayúsculas y minúsculas sin recompilar?
-
20-08-2019 - |
Pregunta
En Python, puedo compilar una expresión regular para que no distinga entre mayúsculas y 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>
¿Hay alguna manera de hacer lo mismo, pero sin usar i
. No puedo encontrar nada como el sufijo m/test/i
de Perl (por ejemplo, <=>) en la documentación.
Otros consejos
También puede realizar búsquedas que no distinguen entre mayúsculas y minúsculas mediante la búsqueda / coincidencia sin el indicador IGNORECASE (probado en Python 2.7.3):
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
El marcador que no distingue entre mayúsculas y minúsculas, (?i)
se puede incorporar directamente en el patrón de expresiones regulares:
>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']
También puede definir mayúsculas y minúsculas durante la compilación del patrón:
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'>
En importaciones
import re
Procesamiento en tiempo de ejecución:
RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):
Cabe mencionar que no usar re.compile
es un desperdicio. Cada vez que se llama al método de coincidencia anterior, se compilará la expresión regular. Esto también es una práctica defectuosa en otros lenguajes de programación. La siguiente es la mejor práctica.
En la inicialización de la aplicación:
self.RE_TEST = re.compile('test', re.IGNORECASE)
Procesamiento en tiempo de ejecución:
if self.RE_TEST.match('TeSt'):
Para realizar operaciones que no distinguen entre mayúsculas y minúsculas, suministre re.IGNORECASE
>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']
y si queremos reemplazar el texto que coincida con el 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'