这一章讲正则表达式比较浅显,想更加大致了解RE,可以看这个网站 http://www.jb51.net/tools/zhengze.html
1. 一般的字符串操作有 index(), count(), find(),replace(),split()函数,复杂的内容则需要正则表达式。
2. re.search(pattern, 'string', re.VERBOSE) 可以给正则表达式添加注释。此种表达方法将忽略空格和注释。
>>> pattern = """
^<span style="white-space:pre"> </span># beginning of string
M{0,4} <span style="white-space:pre"> </span># thousands − 0 to 4 M's
(CM|CD|D?C{0,3}) # hundreds − 900 (CM), 400 (CD), 0−300 (0 to 3 C's),
<span style="white-space:pre"> </span># or 500−800 (D, followed by 0 to 3 C's)
(XC|XL|L?X{0,3})# tens − 90 (XC), 40 (XL), 0−30 (0 to 3 X's),
<span style="white-space:pre"> </span># or 50−80 (L, followed by 0 to 3 X's)
(IX|IV|V?I{0,3})# ones − 9 (IX), 4 (IV), 0−3 (0 to 3 I's),
<span style="white-space:pre"> </span># or 5−8 (V, followed by 0 to 3 I's)
$<span style="white-space:pre"> </span># end of string
"""
3. 罗马数字的I,X,C,M只能重复三次,这要就规定了一些表示的规则, 4只能是IV,不能是IIII。
4. re.search(pattern,'string') 将返回匹配的object, 也可以先将pattern编译,然后对string做search:
>>> phonePattern = re.compile(r'^(\d{3})−(\d{3})−(\d{4})$') #()是re的分组
>>> phonePattern.search('800−555−1212').groups() # groups()显示分组,返回tuple
('800', '555', '1212')
5.一些正则规则:
代码 | 说明 |
---|---|
. | 匹配除换行符以外的任意字符 |
\w | 匹配字母或数字或下划线或汉字 |
\s | 匹配任意的空白符 |
\d | 匹配数字 |
\b | 匹配单词的开始或结束 |
^ | 匹配字符串的开始 |
$ | 匹配字符串的结束 |
详见地址:http://www.jb51.net/tools/zhengze.html