Search code examples
pythonpython-3.xpython-re

is re.compile() still used in python?


i was wondering if re.compile() is still used in python or if there are any new methods or features added to use for regular expressions istead of re.compile(). Because im currently reading a book about python and also watching a course. The book is a little bit old where they teach you about re.compile() togheter with re.search(). while in the Harvard CS50’s Introduction to Programming with Python, which is pretty new, they didnt use re.compile(), but only re.search() for regular expressions.

i searched for documentation for re.compile(), but didnt find answers


Solution

  • Two notes in the docs (https://docs.python.org/3/library/re.html):

    Note The compiled versions of the most recent patterns passed to re.compile() and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

    This is why you often see re.compile not being used, it's not really needed most of the time.

    It is important to note that most regular expression operations are available as module-level functions and methods on compiled regular expressions. The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters.

    For example, note the difference in signatures between the top level function:

    re.match(pattern, string, flags=0)
    

    and the method on a compiled regex object:

    Pattern.match(string[, pos[, endpos]])
    

    In other words, even with caching, re.compile adds the ability to specify pos and endpos.