Python-Ref > Regular expressions (regexp) > Ignoring case in regexps
 
 

<-^^->
Klíčová slova
Moduly

Ignoring case in regexps

How to search without regard for letter case.
By default the Regexps make difference between lower and upper case letters. However it is sometimes convenient to match text regardless of case.
In case only a selected part of a regexp needs to be case-insensitive, it is possible to use standard regexp features to implement this.
Expand/Shrink
Zdroj: (regexp14-1.py)
  1   import re
  2   
  3   text = "It is possible to write XML also as Xml or xml. Some might even use xMl."
  4   
  5   for match in re.findall( "[xX][mM][lL]", text):
  6     print match
stdout:
XML
Xml
xml
xMl
Doba běhu: 22.5 ms
However in more complex cases it is easier to simply tell the regexp to ignore letter case.
Expand/Shrink
Zdroj: (regexp14-2.py)
  1   import re
  2   
  3   text = "It is possible to write XML also as Xml or xml. Some might even use xMl."
  4   
  5   for match in re.findall( "xml", text):
  6     print match
  7   
  8   print "----------"
  9   for match in re.findall( "xml", text, re.IGNORECASE): 
 10     print match
stdout:
xml
----------
XML
Xml
xml
xMl
Doba běhu: 24.4 ms
Unfortunately the sub function does not accept additional options, such as re.IGNORECASE. In this case we need to use compiled regexps.
Expand/Shrink
Zdroj: (regexp14-3.py)
  1   import re
  2   
  3   text = "It is possible to write XML also as Xml or xml. Some might even use xMl."
  4   
  5   print re.sub( "xml", "XML", text)
  6   print re.sub( "xml", "XML", text, re.IGNORECASE) # this does not work, 4th argument is count
  7   print re.compile( "xml", re.IGNORECASE).sub( "XML", text) 
stdout:
It is possible to write XML also as Xml or XML. Some might even use xMl.
It is possible to write XML also as Xml or XML. Some might even use xMl.
It is possible to write XML also as XML or XML. Some might even use XML.
Doba běhu: 51.1 ms