Example 15.10. Compiling regular expressions
-
>>> import re
>>> pattern = '^M?M?M?$'
>>> re.search(pattern, 'M') ------------------------------------------------1
>>> compiledPattern = re.compile(pattern)-----------------------------------2
>>> compiledPattern
>>> dir(compiledPattern)----------------------------------------------------3
['findall', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
>>> compiledPattern.search('M') --------------------------------------------4
-
1.
This is the syntax you've seen before: re.search takes a regular expression as a string (pattern) and a string to match against it ('M'). If the pattern matches, the function returns a match object which can be queried to find out exactly what matched and how
[pope译]这个语法之前你见过: re.search传入字符串格式(pattern)的正则表达式和要被匹配的字符串('M').如果格式符匹配,这个函数返回一个匹配对象它可以被查找到什么匹配和如何匹配。
2.This is the new syntax: re.compile takes a regular expression as a string and returns a pattern object. Note there is no string to match here. Compiling a regular expression has nothing to do with matching it against any specific strings (like 'M'); it only involves the regular expression itself.
[pope译]
这是一个新的语法:re.compile 输入一个正则表达式最为字符串 并返回一个样式对象{pattern object}.记住这里没有字符串匹配过程.编译{compiling}一个正则表达式而在匹配特殊字符串(像'M')上什么也不做.它仅包含正则表达式本身。
3.
The compiled pattern object returned from re.compile has several useful-looking functions, including several (like search and sub) that are available directly in the re module.
[pope译]
这个compiledpattern 对象返回来自于re.complie 的几个 看来有用的方法, 比如 在re模块中 几个(像 search 和 sub)直接的有用的方法。
4.
Calling the compiled pattern object's search function with the string 'M' accomplishes the same thing as calling re.search with both the regular expression and the string 'M'. Only much, much faster. (In fact, the re.search function simply compiles the regular expression and calls the resulting pattern object's search method for you.)
[pope译]
调用这个compiledPattern 对象的search 方法查找字符'M' 达到{accomplishe} 和调用re.search 同样的效果 ,都是正则表达查找'M'.仅仅是更快了。(实际上,这个re.search 方法简单地编译了正则表达式并且 为你调用了匹配样本对象的search方法的结果)
[pope译]
无论何时你打算使用正则表达式多余一次,你应该编译它获得一个待匹配{pattern}对象,在需要匹配的位置直接调用它。
-
1.
没有评论:
发表评论