Search code examples
pythonregexcase-insensitive

Python regex partially case insensitive


How to do it in nice short way? I have 2 strings and I want to search one in another, but:

  • lowercase letter matches to lower- and uppercase
  • uppercase letter matches only to uppercase.

Example:

"abcd" matches to "AbCd", "ABCD", or "abcd"

"Abcd" matches to "Abcd", "ABcd" and so on, but not matches to "abcd"


Solution

  • You need to transform your regular expressions, something like

    def transform(regex):
        return ''.join([
            "[%s%s]" % (c, c.upper())
                if c.islower()
                else c
            for c in regex
        ])
    
    
    transformed = transform('Abcd')
    

    Will transform the regex Abcd into A[bB][cC][dD].

    Of course this does not work, if your actual regex does have character classes [a-z] already.