Python Regular precompiled Expression re.compile () __python

Source: Internet
Author: User

It is more efficient to compile these expressions for expressions that are frequently used by programs. The compile () function converts an expression string into a regexobject.

The following example is derived from the Python standard library:


Import re


# precompile the patterns
regexes = [Re.compile (p)
for P in [' Here ', ' that ']
]
Text = "Does this text match"
?     print ' text:%r\n '% repr (text)
for regex in
regexes: print ' seeking '%s '-> '% Regex.pattern    If Regex.search (text):
print ' match! '
else:
print ' no match '



Output:

Text: "' Does this text match the pattern? '"


Seeking "this"-> match!
Seeking "that"-> no match


Module-level functions maintain a cache of compiled expressions. However, the size of this cache is limited, and using compiled expressions directly avoids the cache lookup overhead. Another benefit of using compiled expressions is that by precompiling all expressions while loading a module, you can turn the compilation work to the beginning of the application, rather than to compile when the program responds to a user action.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.