Home > Net >  How to do a literal RegEx search ignoring case in Python
How to do a literal RegEx search ignoring case in Python

Time:03-19

Using Python 3.9 on MacOS (if it matters) I have the following boolean test that uses regular expressions to search for a pattern in a string:

found = bool(re.search(pattern, string, re.IGNORECASE))

This boolean is not a literal search. For example, the strings Z97.11 and Z98.811 come back with a pattern of .1. And that is correct for a regular expression - but I want the boolean to be true with Z97.11 only and not Z98.811 for a literal search using re.search.

The literal search also has to be case insensitive.

CodePudding user response:

If you're regular expression contains . without a backslash preceding it, then you're matching any character. So searching for .1 against 81 will succeed.

change .1 to \1. in your regular expression, and only Z97.11 should come through.

very useful resource: https://regex101.com/

CodePudding user response:

Your regular expression would be \.1 if you're looking for the presence of the literal substring .1. . has a special meaning in regex (it means any character except newline). Using a backslash (\) will escape the special meaning of the . character in regex.

found = re.search(r"\.1", string, re.IGNORECASE) is not None

I normally prefer to test out my regex patterns at regexr.com to help quickly write these expressions. I hope this site helps you too!

Example of using RegExr.com

  • Related