python 中的 re.compile 函数
source link: https://www.cnblogs.com/nomorewzx/p/4203829.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
正则表达式功能十分强大。
“有些人面临一个问题时会想:‘我知道,可以用正则表达式来解决这个问题。’于是现在他们就有两个问题了”——Jamie Zawinski
同时正则表达式很难掌握。
正则表达式的各种规则就不在此赘述了,以下介绍在python的re模块中怎样应用正则表达式
1. 使用re.compile
re模块中包含一个重要函数是compile(pattern [, flags]) ,该函数根据包含的正则表达式的字符串创建模式对象。可以实现更有效率的匹配。在直接使用字符串表示的正则表达式进行search,match和findall操作时,python会将字符串转换为正则表达式对象。而使用compile完成一次转换之后,在每次使用模式的时候就不用重复转换。当然,使用re.compile()函数进行转换后,re.search(pattern, string)的调用方式就转换为 pattern.search(string)的调用方式。
其中,后一种调用方式中,pattern是用compile创建的模式对象。如下:
>>> import re >>> some_text = 'a,b,,,,c d' >>> reObj = re.compile('[, ]+') >>> reObj.split(some_text) ['a', 'b', 'c', 'd']
2.不使用re.compile
在进行search,match等操作前不适用compile函数,会导致重复使用模式时,需要对模式进行重复的转换。降低匹配速度。而此种方法的调用方式,更为直观。如下:
>>> import re >>> some_text = 'a,b,,,,c d' >>> re.split('[, ]+',some_text) ['a', 'b', 'c', 'd']
Recommend
-
108
Is it possible for let's say open source programs to install malware at compile time? I'm thinking of C macros or makefile related stuff that will execu...
-
153
Idris Vimscript! The good stuff. Please note that this is very experimental. For example, the Idris Integer type, usually represented as an arbitrary-precision integer, is represented using the Vim num...
-
110
Error Prone Error Prone is a static analysis tool for Java that catches common programming mistakes at compile-time. public class ShortSet { public static void main (String[] args) { Set<Short> s = new HashSet&l...
-
172
qt.go - Qt binding for Go (Golang) aims get Go's compile speed again.
-
59
GitHub is where people build software. More than 27 million people use GitHub to discover, fork, and contribute to over 80 million projects.
-
61
In this blog post, I would like to present a research project I have been working on: Trying to use QML from Rust, and in general, using a C++ library from Rust. The project is a Rust crate which al...
-
81
arm_now is a qemu powered tool that allows instant setup of virtual machines on arm cpu, mips, powerpc, nios2, x86 and more, for reverse, exploit, fuzzing and programming purpose.
-
61
Using new Babel 7 and preset-typescript to compile Angular 6 app Recent launch of Babel 7 was accompanied by a pretty large fanfare, mostly due to long time since last release. Previous ver...
-
40
switch/case for Strings Tobias Hoffmann C++ User Treffen Aachen, 2018-09-13
-
11
Compile vim 7.3 on Mac for Python Nov 9, 2010 之所以想编译安装 vim 是因为一个 python vim script 需要 +python 支持,而 Mac 下默认的 vim 7.2 并没有 +python,所以每次 vim xx.py 的时候都会有一个警...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK