Python读书笔记(一)---正则表达式

官方文档:http://docs.python.org/library/re.html#re.MatchObject

正则表达式是用来处理字符串的强大工具,python通过re模块提供对正则表达式的支持。使用re的方法有2种方式:

1.将正则表达式的字符串形式编译为Pattern实例,使用compile函数

>>> import re
>>> p = re.compile(r'(...)+')
>>> n = p.match("a1b2c3d4e5f6")
>>> n.group(1)
'5f6'

在使用compile函数时,可以设置匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。 

可选值有:

    • re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
    • M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
    • S(DOTALL): 点任意匹配模式,改变'.'的行为
    • L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
    • U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
    • X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式是等价的:

2.直接使用函数

>>> import re
>>> m = re.match(r'(..)+', 'a1b2c3')
>>> m.group(1)
'c3'

在上面的例子中使用到了match函数,用来匹配字符串,match函数的使用方式为:

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]): 

这个方法将从string的pos下标处起尝试匹配pattern;如果pattern结束时仍可匹配,则返回一个Match对象;如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None

除了match函数以外,还有如下几个函数

search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): 

这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。 

group()以及groups()是常用的匹配对象的方法,group() 同group(0)就是匹配正则表达式整体结果,group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。也就是说如果规则中只有一个括号(上例所示),那么group(2)执行时会出现IndexError。而groups()返回所有括号匹配的字符,以tuple格式。

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): 

按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 
搜索string,以列表形式返回全部能匹配的子串。

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): 
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。 

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 
使用repl替换string中每一个匹配的子串后返回替换后的字符串。

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): 
返回 (sub(repl, string[, count]), 替换次数)。

 

 

参考资料:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

posted @ 2017-05-11 13:12  哈利波波特  阅读(12)  评论(0)    收藏  举报