Is it worth using Python's re.compile?

前端 未结 26 2204
旧时难觅i
旧时难觅i 2020-11-22 12:51

Is there any benefit in using compile for regular expressions in Python?

h = re.compile(\'hello\')
h.match(\'hello world\')

vs



        
26条回答
  •  再見小時候
    2020-11-22 13:18

    I really respect all the above answers. From my opinion Yes! For sure it is worth to use re.compile instead of compiling the regex, again and again, every time.

    Using re.compile makes your code more dynamic, as you can call the already compiled regex, instead of compiling again and aagain. This thing benefits you in cases:

    1. Processor Efforts
    2. Time Complexity.
    3. Makes regex Universal.(can be used in findall, search, match)
    4. And makes your program looks cool.

    Example :

      example_string = "The room number of her room is 26A7B."
      find_alpha_numeric_string = re.compile(r"\b\w+\b")
    

    Using in Findall

     find_alpha_numeric_string.findall(example_string)
    

    Using in search

      find_alpha_numeric_string.search(example_string)
    

    Similarly you can use it for: Match and Substitute

提交回复
热议问题