Python compiles regular expressions to improve efficiency in a detailed way

Source: Internet
Author: User
Python is a cool language, because you can do a lot of things with very little code in a very short period of time, plus regular expressions to better reflect the results, the following article is mainly about Python in the pre-compiled regular expressions to improve the efficiency of the relevant data, You need a friend to refer to below.

Objective

In the regular expression module of RE, the regular expression can be accessed through a module, but if you use regular expressions repeatedly, it is better to use the compile function to compile the regular expression into object Regexobject, which will greatly improve the efficiency of the search. Because access is based on non-compiled methods, it is done using a small piece of buffering in the module.

As in the following example:


Import re  # precompile the Patterns regexes = [  re.compile (P)  for P in [' This ', ' that ']] text = ' Http://blog. Csdn.net/caimouse is great blog, the Is my blog. '  Print (' text: {!r}\n '. Format (text))  for the regex in Regexes:  print (' Seeking ' {} '. Format (Regex.pattern),    end= ")   If Regex.search (text):   print (' match! ')  else:   print (' no match ')

The resulting output is as follows:


text: ' Http://blog.csdn.net/caimouse is great blog, the Is my blog. ' Seeking ' this ' match ! Seeking "that", no match 
Related Article

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.