蒦嗳伱 发表于 2015-4-22 01:35:38

【循序渐进学Python】12.Python 正则表达式简介

  正表达式就是一段匹配文本片段的模式,在Python 中 re 模块包含了对正则表达式(regular expression)的支持。

1. 正则表达式的基本概念
  1. 通配符
  点号( . )可以匹配换行符之外的任何单个字符,被称之为通配符。
  
  2. 特殊字符转义
  将有特殊含义的字符作为普通字符使用时需要进行转义。例如想要匹配 python.org时需要将表达式写为: python\\.org 才行。
  为什么使用两个反斜线?

  这是为了通过解释器进行转义,需要进行两个级别的转义:1.通过解释器的转义;2.通过 re 模块转义。如果不想使用两个反斜线,可以考虑使用原始字符串,如:r'python\.org'。

  
  3. 字符集
  字符集是在中括号( [] )中包含字符串。字符集可以匹配它所包含的任意字符。即'ython'可以匹配 python 和 jython 。
  使用范围

  可以使用范围,如 '' 可以匹配 a 到 z 的任意一个字符。'a-zA-Z0-9' 可以匹配任意大小写的一个字母或数字。

  
  反转字符集

  我们也可以对字符集进行反转,比如 '[^abc]' 匹配除了a、b和c之外的任何字符。

  
  字符集中的特殊字符
  特殊字符在模式中做文本字符,而不是正则表达式运算符的话需要对其进行转义。但是在字符集中并不需要,只有以三种情况下,需要将特殊字符作为普通文本使用时,需要对字符进行转义:


[*]^ 脱字符作为字符集的开头
[*]] 右中括号作为字符集的开头
[*]- 横线(字符范围)作为字符集的开头
  
  4. 选择符合子模式
  管道符号( | )是用于选择项的特殊字符。例如: 'python|ruby' 匹配python和ruby这两个单词。
  子模式(subparttern)是指:使用圆括号将选择项括起来。例如 'p(ython|erl)' 匹配python和perl。
  
  5. 可选项和重复子模式
  在子模式后面加上一个问号,它就变成了一个可选项,例如:



r'(http://)?(www\.)?python\.org$'
  
  上面的模式只能匹配下面的字符串:



'http://www.python.org'
'http://python.org'
'www.python.org'
'python.org'
  
  问号表示子模式可以出现一次或者根本不出现,下面的运算符允许子模式重复多次:


[*](pattern)*: 允许模式重复0次或多次
[*](pattern)+: 允许模式出现一次或多次
[*](pattern){m-n}: 允许模式重复m~n次
  
  6. 字符串的开始和结尾
  使用 ^ 脱字符标记字符串开始;使用美元符号 $ 标识字符串的结尾。如:



'^Python$'
  

2. re 模块
  re 模块包含了很多操作正则表达式的函数,以下是其中最常用的函数:



1 compile(pattern[, flags])               根据包含正则表达式的字符串创建模式对象
2 search(pattern, string[, flags])      在字符串中寻找模式
3 match(pattern, string[, flags])         在字符串的开始处匹配模式
4 split(pattern, string[, maxsplit=0])    根据模式的匹配项来分割字符串
5 findall(pattern, string)                列出字符串中模式的所有匹配项
6 sub(pat, repl, string[, count=0])       将字符串中所有pat的匹配项用repl替换
7 escape(string)                        将字符串中所有特殊正则表达式字符转义
  
  下面是这些函数的的简单示例:



1 # --coding: utf-8 --
2 import re
3
4 # search
5 pattern = r'(http://)?(www\.)?python\.org$'
6 string = 'python.org'
7 if re.search(pattern,string):
8   print 'found it'
9
10 # match
11 text = 'alpha,beta,,,,,,gamma delta'
12 pattern = '[,]+' # 注意+号
13 print re.split(pattern,text) # ['alpha', 'beta', 'gamma delta']
14
15 # findall
16 pattern = '+' # 匹配单词
17 text = '"Hm... Err -- are you sure?" he said, sounding insecure.'
18 # ['Hm', 'Err', 'are', 'you', 'sure', 'he', 'said', 'sounding', 'insecure']
19 print re.findall(pattern,text)
20
21 pattern = r'[.?\-",]' # 匹配标点符号
22 # ['"', '.', '.', '.', '-', '-', '?', '"', ',', '.']
23 print re.findall(pattern,text)
24
25 # sub
26 pattern = '{name}'
27 text = 'Dear {name}...'
28 print re.sub(pattern, 'Mr. Gumby', text) # Dear Mr. Gumby...
29
30 # escape
31 print re.escape('www.python.org') # www\.python\.org
32 print re.escape('But where is the ambiguity?') # But\ where\ is\ the\ ambiguity\?
  

2.1 匹配对象和组
  当 re 模块中对字符串进行匹配的函数找到匹配项时,就会返回一个 MatchObject 对象。
  
  组的概念
  该对象包含了匹配模式的子字符串的信息,这些信息由组(group)构成。简而言之,组就是放置在圆括号内的子模式。组的序号取决于它左侧的括号数。组0就是整个模式。在下面的模式中:



'There (was a (wee) (cooper)) who (lived in Fyfe)'
  
  包含这些组:



0   There was a wee cooper who lived in Fyfe
1   was a wee cooper
2   wee
3   cooper
4   lived in Fyfe
  
  下面是 re 匹配对象的常用方法:



1 group(, ...])         获取给定子模式(组)的匹配项
2 start()                  返回给定组匹配项的开始位置(返回结果是索引从0开始)
3 end()                      返回给定组匹配项的结束位置(返回结果是索引加1,和分片一样,不包括组的结束位置)
4 span()                   返回一个组的开始和结束位置
  
  示例如下:



1 import re
2
3 m = re.match(r'www\.(.*)\..{3}','www.python.org')
4 print m.group(1) # python
5 print m.start(1) # 4
6 print m.end(1) # 10
7 print m.span(1) # (4, 10)
  

  除了整体匹配以为(组0),只能使用99个组,即组的范围在1-99之间

  

2.2 使用re的替换函数
  通过使用 re.sub 函数和组号的结合,还可以实现更加复杂的字符串提供功能,如下所示:



import re
emphasis_pattern = r'\*([^\*]+)\*'
# hello, world!
print re.sub(emphasis_pattern,r'\1','hello, *world*!')
  
  贪婪模式和非贪婪模式
  重复运算符默认是贪婪的( greedy),它会进行尽可能多的匹配。如下面的模式使用的就是贪婪模式:



1 import re
2
3 emphasis_pattern = r'\*(.+)\*'
4 text = '*This* is *it*'
5 # This* is *it
6 print re.sub(emphasis_pattern,r'\1',text)
  
  非贪婪模式和贪婪模式相反,它会尽可能少的匹配。将重复运算符变成非贪婪模式只需要在其后加一个问号( ? )即可:



1 import re
2
3 emphasis_pattern = r'\*(.+?)\*'
4 text = '*This* is *it*'
5 # This is it
6 print re.sub(emphasis_pattern,r'\1',text)
  

参考资料&进一步阅读
  Python Doc —— re 模块
  Python基础教程(第二版)
页: [1]
查看完整版本: 【循序渐进学Python】12.Python 正则表达式简介