本文不涉及正则表达式本身的内容,只记一下python中正则的用法及常用方法。
一、re模块python中用re模块进行正则处理
>>>importre>>>s = r'abc'>>>re.findall(s,'aaaabcaaaaa')
['abc']
或先编译(会更快):
>>>importre>>> r1 = re.compile(r'abc', re.I)>>> re.findall(r1,'ababcabd')
['abc']#或用下面的方式>>>r1.findall('ababcabd')['abc']
常用编译标志:
二、常用方法1、compile:对正则进行编译,使运行速度加快,用法如上
2、match:决定RE是否在字符串刚开始的位置,返回的是Match object对象,没匹配到返回None
3、search:扫描字符串,找到这个 RE 匹配的位置,返回的是Match object对象,没匹配到返回None
4、findall:找到RE匹配的所有子串,作为列表返回
5、finditer:找到RE匹配的所有子串,作为迭代器返回,迭代器中是 Match object对象
6、sub(regex,replace【可以是函数】,content,count=0【可选,替换的数量,默认为全部】,flags=0【可选,正则参数,如re.I】):数据替换
详细参考:http://www.crifan.com/python_re_sub_detailed_introduction/
7、subn(regex,replace,content,count=0,flags=0):跟sub相同,只是返回值中包含替换次数
8、split(string [, maxsplit = 0]):把字符串按正则分隔
三、Match object 中常用方法1、group():返回被RE匹配的字符串
2、start():返回匹配的开始的位置
3、end():返回匹配结束的位置
4、span():返回一个元组包含匹配(开始和结束)的位置
示例:
importre
m= re.match(r'(\w+) (\w+)(?P<sign>.*)','hello world!')PRint"m.string:", m.stringprint"m.re:", m.reprint"m.pos:", m.posprint"m.endpos:", m.endposprint"m.lastindex:", m.lastindexprint"m.lastgroup:", m.lastgroupprint"m.group(1,2):", m.group(1, 2)print"m.groups():", m.groups()print"m.groupdict():", m.groupdict()print"m.start(2):", m.start(2)print"m.end(2):", m.end(2)print"m.span(2):", m.span(2)printr"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3')### output ####m.string: hello world!#m.re: <_sre.SRE_Pattern object at 0x016E1A38>#m.pos: 0#m.endpos: 12#m.lastindex: 3#m.lastgroup: sign
#m.group(1,2): ('hello', 'world')#m.groups(): ('hello', 'world', '!')#m.groupdict(): {'sign': '!'}#m.start(2): 6#m.end(2): 11#m.span(2): (6, 11)#m.expand(r'\2 \1\3'): world hello!