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.
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?
CodePudding user response:
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.