Categories
Python Answers

How to create case insensitive regular expression without re.compile with Python?

Spread the love

Sometimes, we want to create case insensitive regular expression without re.compile with Python.

In this article, we’ll look at how to create case insensitive regular expression without re.compile with Python.

How to create case insensitive regular expression without re.compile with Python?

To create case insensitive regular expression without re.compile with Python, we can pass in re.IGNORECASE to re.search, re.match, and re.sub.

For instance, we write

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'foo', 'Testing', flags=re.IGNORECASE)

to call the 3 methods with a regex string and the re.IGNORECASE flag to make them search for matches for a pattern ignoring the case.

Conclusion

To create case insensitive regular expression without re.compile with Python, we can pass in re.IGNORECASE to re.search, re.match, and re.sub.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *