Python正则表达式

来源:互联网 发布:ledv3.zh3软件下载 编辑:程序博客网 时间:2024/06/05 08:00
#encoding:utf-8'''python正则表达式:一个特殊的字符序列作用:方便查找一个字符串是否与某种模式匹配re模块使python语言拥有全部的正则表达式功能'''import re'''re.rematch(pattern,string,flag=0)pattern:匹配的正则表达式string:要匹配的字符串flag:标志位,用于控制正则表达式匹配的方式,如区分大小写,多行匹配返回值:如果匹配成功,则返回匹配对象,否则返回None'''def test_rematch():    passdef test_findall():    s='hello world,hello world'    r=r'hello'    print re.findall('world',s)   #['world', 'world']    print re.findall(r,s)         #['hello', 'hello']    r=r'^hello' # ^匹配行首    print re.findall(r,s)   #['hello']    r=r'x[0-9]x'    print re.findall(r,'x1x')  #['x1x']    r=r'^abc'    print re.findall(r,'^abc') #[]    r='\^abc'    print re.findall(r,'^abc')  #['^abc']    r=r'\^abc'    print re.findall(r,'^abc')  #['^abc']    passdef test_s1():    '''    \:表示不同特殊意义的字符或者取消所有元字符    r'[0-9]'=r'\d'    \D:相当于[^0-9]    \s:匹配任何空白字符 [\n\t\r\f\v]    \S:匹配任何非空白字符    \w:匹配任何字符数字字符  [a-zA-Z0-9]    \W:匹配任何非字母非数字字符    '''    '''    先编译,再匹配。速度快    '''    r1=r'\d{3,4}-?\d{8}'    p_tel=re.compile(r1)    print type(p_tel)    print p_tel.findall('010-12345678')    passdef test_sub():    '''    sub函数用于字符替换    '''    s='hello csvt'    print s.replace('csvt','python')  #hello python    rs=r'c..t'    print re.sub(rs,'python','csvt caat cvvt cccc')  #python python python ccccif __name__=='__main__':    #test_findall()    #test_s1()    test_sub()    print r'\nabc'   #\nabc    print '\\'  #\    print r'\\'  #\\