== re 模块==

        "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."

        - Jamie Zawinski, on comp.lang.emacs

``re`` 模块提供了一系列功能强大的正则表达式 (regular expression) 工具,
它们允许你快速检查给定字符串是否与给定的模式匹配 (使用 ``match`` 函数),
或者包含这个模式 (使用 ``search`` 函数). 正则表达式是以紧凑(也很神秘)的语法写出的字符串模式. ``match`` 尝试从字符串的起始匹配一个模式, 如 [Example 1-54 #eg-1-54] 所示.
如果模式匹配了某些内容 (包括空字符串, 如果模式允许的话) ,
它将返回一个匹配对象. 使用它的 ``group`` 方法可以找出匹配的内容. ====Example 1-54. 使用 re 模块来匹配字符串====[eg-1-54] ```
File: re-example-1.py import re text = "The Attila the Hun Show" # a single character 单个字符
m = re.match(".", text)
if m: print repr("."), "=>", repr(m.group(0)) # any string of characters 任何字符串
m = re.match(".*", text)
if m: print repr(".*"), "=>", repr(m.group(0)) # a string of letters (at least one) 只包含字母的字符串(至少一个)
m = re.match("\w+", text)
if m: print repr("\w+"), "=>", repr(m.group(0)) # a string of digits 只包含数字的字符串
m = re.match("\d+", text)
if m: print repr("\d+"), "=>", repr(m.group(0)) *B* '.' => 'T'
'.*' => 'The Attila the Hun Show'
'\\w+' => 'The'*b*
``` 可以使用圆括号在模式中标记区域. 找到匹配后, ``group`` 方法可以抽取这些区域的内容,
如 [Example 1-55 #eg-1-55] 所示. ``group(1)`` 会返回第一组的内容, ``group(2)``
返回第二组的内容, 这样... 如果你传递多个组数给 ``group`` 函数, 它会返回一个元组. ====Example 1-55. 使用 re 模块抽出匹配的子字符串====[eg-1-55] ```
File: re-example-2.py import re text ="10/15/99" m = re.match("(\d{2})/(\d{2})/(\d{2,4})", text)
if m:
print m.group(1, 2, 3) *B*('10', '15', '99')*b*
``` ``search`` 函数会在字符串内查找模式匹配, 如 [Example 1-56 #eg-1-56] 所示.
它在所有可能的字符位置尝试匹配模式, 从最左边开始, 一旦找到匹配就返回一个匹配对象.
如果没有找到相应的匹配, 就返回 //None// . ====Example 1-56. 使用 re 模块搜索子字符串====[eg-1-56] ```
File: re-example-3.py import re text = "Example 3: There is 1 date 10/25/95 in here!" m = re.search("(\d{1,2})/(\d{1,2})/(\d{2,4})", text) print m.group(1), m.group(2), m.group(3) month, day, year = m.group(1, 2, 3)
print month, day, year date = m.group(0)
print date *B*10 25 95
10 25 95
10/25/95*b*
``` [Example 1-57 #eg-1-57] 中展示了 ``sub`` 函数, 它可以使用另个字符串替代匹配模式. ====Example 1-57. 使用 re 模块替换子字符串====[eg-1-57] ```
File: re-example-4.py import re text = "you're no fun anymore..." # literal replace (string.replace is faster)
# 文字替换 (string.replace 速度更快)
print re.sub("fun", "entertaining", text) # collapse all non-letter sequences to a single dash
# 将所有非字母序列转换为一个"-"(dansh,破折号)
print re.sub("[^\w]+", "-", text) # convert all words to beeps
# 将所有单词替换为 BEEP
print re.sub("\S+", "-BEEP-", text) *B*you're no entertaining anymore...
you-re-no-fun-anymore-
-BEEP- -BEEP- -BEEP- -BEEP-*b*
``` 你也可以通过回调 (callback) 函数使用 ``sub`` 来替换指定模式.
[Example 1-58 #eg-1-58] 展示了如何预编译模式. ====Example 1-58. 使用 re 模块替换字符串(通过回调函数)====[eg-1-58] ```
File: re-example-5.py import re
import string text = "a line of text\\012another line of text\\012etc..." def octal(match):
# replace octal code with corresponding ASCII character
# 使用对应 ASCII 字符替换八进制代码
return chr(string.atoi(match.group(1), 8)) octal_pattern = re.compile(r"\\(\d\d\d)") print text
print octal_pattern.sub(octal, text) *B*a line of text\012another line of text\012etc...
a line of text
another line of text
etc...*b*
``` 如果你不编译, ``re`` 模块会为你缓存一个编译后版本, 所有的小脚本中,
通常不需要编译正则表达式. Python1.5.2 中, 缓存中可以容纳 20 个匹配模式, 而在 2.0 中,
缓存则可以容纳 100 个匹配模式. 最后, [Example 1-59 #eg-1-59] 用一个模式列表匹配一个字符串. 这些模式将会组合为一个模式, 并预编译以节省时间. ====Example 1-59. 使用 re 模块匹配多个模式中的一个====[eg-1-59] ```
File: re-example-6.py import re, string def combined_pattern(patterns):
p = re.compile(
string.join(map(lambda x: "("+x+")", patterns), "|")
)
def fixup(v, m=p.match, r=range(0,len(patterns))):
try:
regs = m(v).regs
except AttributeError:
return None # no match, so m.regs will fail
else:
for i in r:
if regs[i+1] != (-1, -1):
return i
return fixup #
# try it out! patterns = [
r"\d+",
r"abc\d{2,4}",
r"p\w+"
] p = combined_pattern(patterns) print p("129391")
print p("abc800")
print p("abc1600")
print p("python")
print p("perl")
print p("tcl") *B*0
1
1
2
2
None*b*
```

  

python标准库介绍——5 re模块详解的更多相关文章

  1. python标准库介绍——27 random 模块详解

    ==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...

  2. python标准库介绍——12 time 模块详解

    ==time 模块== ``time`` 模块提供了一些处理日期和一天内时间的函数. 它是建立在 C 运行时库的简单封装. 给定的日期和时间可以被表示为浮点型(从参考时间, 通常是 1970.1.1 ...

  3. python标准库介绍——10 sys 模块详解

    ==sys 模块== ``sys`` 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. === 处理命令行参数=== 在解释器启动后, ``argv`` 列表包含了传递给脚本的所有 ...

  4. python标准库介绍——30 code 模块详解

    ==code 模块== ``code`` 模块提供了一些用于模拟标准交互解释器行为的函数. ``compile_command`` 与内建 ``compile`` 函数行为相似, 但它会通过测试来保证 ...

  5. python标准库介绍——8 operator 模块详解

    ==operator 模块== ``operator`` 模块为 Python 提供了一个 "功能性" 的标准操作符接口. 当使用 ``map`` 以及 ``filter`` 一类 ...

  6. python标准库介绍——36 popen2 模块详解

    ==popen2 模块== ``popen2`` 模块允许你执行外部命令, 并通过流来分别访问它的 ``stdin`` 和 ``stdout`` ( 可能还有 ``stderr`` ). 在 pyth ...

  7. python标准库介绍——23 UserString 模块详解

    ==UserString 模块== (2.0 新增) ``UserString`` 模块包含两个类, //UserString// 和 //MutableString// . 前者是对标准字符串类型的 ...

  8. python标准库介绍——22 UserList 模块详解

    ==UserList 模块== ``UserList`` 模块包含了一个可继承的列表类 (事实上是对内建列表类型的 Python 封装). 在 [Example 2-16 #eg-2-16] 中, / ...

  9. python标准库介绍——21 UserDict 模块详解

    ==UserDict 模块== ``UserDict`` 模块包含了一个可继承的字典类 (事实上是对内建字典类型的 Python 封装). [Example 2-15 #eg-2-15] 展示了一个增 ...

  10. python标准库介绍——20 cStringIO 模块详解

    ==cStringIO 模块== ``cStringIO`` 是一个可选的模块, 是 ``StringIO`` 的更快速实现. 它的工作方式和 ``StringIO`` 基本相同, 但是它不可以被继承 ...

随机推荐

  1. 如何在Linux上安装服务器管理软件Cockpit

    Cockpit 是一个自由开源的服务器管理软件,使得我们可以通过它好看的 Web 前端界面轻松地管理我们的 GNU/Linux 服务器,非常轻量级,Web 界面也非常简单易用. Cockpit 使得 ...

  2. 【nodejs】用express又做了份crud

    感觉crud是高级形式的hello world了. app代码: 'use strict'; var express=require('express'); var http=require('htt ...

  3. HDU1698:Just a Hook(线段树区间更新)

    Problem Description In the game of DotA, Pudge’s meat hook is actually the most horrible thing for m ...

  4. TQ2440之定时器中断0——volatile关键字的重要作用

    近日,在学习<ARM处理器裸机开发实战--机制而非策略>一书,在TQ2440开发板上,按照书中实例以及光盘配套程序源代码进行Timer0中断试验,编译成功后烧写到开发板上,没有任何反应,反 ...

  5. CSDN日报20170310——《假如我是一行代码》

    [程序人生]假如我是一行代码 作者:henry-hacker 我们不止一次在生活中听到"假如我如何如何,我会如何如何"的句式.而这种句式说出来的一般意义无非就是让我们站在还有一个角 ...

  6. 如何分析Java虚拟机死锁

    Thread Dump and Concurrency Locks Thread dumps are very useful for diagnosing synchronization relate ...

  7. line-height测量及使用

    1.line-height定义 line-height表示行高,即两行文字基线间的距离. 以下是图示说明: 行高是2条红线之间的距离,即:1+2+3+4 在实际测量中,基线不好找,可测量顶线到顶线的距 ...

  8. 深入理解 Linux 内存管理

    1. 内存地址 以Intel的中央处理器为例,Linux 32位的系统中.物理内存的基本单位是字节(Byte),1个字节有8个二进制位. 每一个内存地址指向一个字节,内存地址加1后得到下一个字节的地址 ...

  9. Flash:DisplayObject的矩阵旋转(移动/修改注册点,修改旋转点)

    简单来说,原理就是利用matrix运算,先把旋转点移到原点位置,旋转变换后再恢复到原来的位置 var a:Sprite = new Sprite(); a.graphics.beginFill(0); ...

  10. Loader拉取图片,由于redirect重定向,导致策略文件无效 设置checkPolicyFile后还是无效:需要一个策略文件,但在加载此媒体时未设置 checkPolicyFile 标志

    大家好,在这里分享一下flash里边处理redirect的方法. 一般而言,大家不会遇到这个问题,毕竟图片地址一般杠杠的,不会redirect.但昨天在拉取空间的照片就会出现redirect.神啊!! ...