Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make the regex pipe character matching less case sensitive

I am trying to create a regex code that allows me match and retrieve data from a string regardless of the case in which the required data occurs.

Using the code below, I get the desired output i.e. a tuple with 3 items that can be retrieved using indices.

    import re 

    RegexNumber =  re.compile(r'bat(mobile|girl|cave)')
    mo  = RegexNumber.search("Into the batmobile, batgirl. And then later to the batcave")

    print(mo.group(0))
    print(mo.group(1))
    print(mo.group(2))

However when I capitalize the prefix to the Regex code (i.e. change "bat" to "Bat"), I get a "Nonetype" error when I run the code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to pass an object (RegString1) created using the .istitle() method into the .search() method as seen below, but apparently the .search() method only recognizes string format. I get a Type Error: expected string or byte object.

    import re 

    RegexNumber =  re.compile(r'Bat(mobile|girl|cave)')
    RegString = "Into the batmobile, batgirl. And then later to the batcave"
    RegString1 = RegString.istitle()
    mo  = RegexNumber.search(RegString1)

    print(mo.group(0))

Please how can I teak this code to make my Regex object less case sensitive?

>Solution :

Try handing a flag to regex like this:

RegexNumber = re.compile(r'bat(mobile|girl|cave)', re.IGNORECASE)

Your approach using istitle() does not work because you call it on your whole string, it returns False (see method definition for why), then you hand that Boolean value to regex and regex throws the error that it expects a string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading