Home > Backend Development > Python Tutorial > Detailed explanation of how to improve efficiency of compiling regular expressions in python

Detailed explanation of how to improve efficiency of compiling regular expressions in python

巴扎黑
Release: 2017-09-26 10:39:48
Original
3803 people have browsed it

Python is a cool language, because you can do a lot of things with very little code in a short time, and regular expressions can better reflect its effect. The following article mainly introduces it to you. I have related information about improving efficiency by pre-compiling regular expressions in python. Friends in need can refer to it.

Preface

In the re regular expression module, you can access regular expressions through the module, but if it is repeated multiple times To use regular expressions properly, it is best to use the compile function to compile the regular expression into an object RegexObject. This will greatly improve the efficiency of the search, because when accessed in a non-compiled way, a small buffer in the module is used. .

For example:


##

import re 
 
# Precompile the patterns 
regexes = [ 
 re.compile(p) 
 for p in ['this', 'that'] 
] 
text = 'http://blog.csdn.net/caimouse is great blog, this is my blog.' 
 
print('Text: {!r}\n'.format(text)) 
 
for regex in regexes: 
 print('Seeking "{}" ->'.format(regex.pattern), 
   end=' ') 
 
 if regex.search(text): 
  print('match!') 
 else: 
  print('no match')
Copy after login

The result output is as follows:



Text: 'http://blog.csdn.net/caimouse is great blog, this is my blog.'


Seeking "this" -> match!
Seeking "that" -> no match
Copy after login

The above is the detailed content of Detailed explanation of how to improve efficiency of compiling regular expressions in python. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template