0

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

InSync
  • 4,851
  • 4
  • 8
  • 30
iva
  • 3
  • 4
  • 2
    You can use re.compile when it is beneficial. See all the discussion here [link](https://stackoverflow.com/questions/47268595/when-to-use-re-compile#47269110) – user19077881 Aug 12 '23 at 10:01
  • 2
    The Python official documentation is a good start: https://docs.python.org/3/library/re.html#re.compile *"Using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program... programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions."* – slothrop Aug 12 '23 at 10:01

1 Answers1

0

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.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89