• New-Python-模块之re其他


    1、search:与findall用法完全一致,不一样的地方在于search匹配一次就结束

    print(re.search('alex','alex say hello alex').group())
    
    alex
    匹配的是一个对象,拿到这个值,需要调group

    2、match:match代表从头匹配

    print(re.match('alex','alex say hello alex').group())
    print(re.match('alex',' alex say hello alex').group())
    
    相当于:
    print(re.search('^alex','alex say hello alex').group())

    3、split

    print(re.split(':','root:x:0:0:/root::/bin/bash'))
    
    ['root', 'x', '0', '0', '/root', '', '/bin/bash']

    4、sub---替换

    print(re.sub('alex','SB','alex say i have on telsa my name is alex',1))
    print(re.subn('alex','SB','alex say i have on telsa my name is alex'))
    #后面1意思是替换一次,默认全部替换;
    
    #subn:可以显示替换了几次:
    
    SB say i have on telsa my name is alex
    ('SB say i have on telsa my name is SB', 2)
    print(re.sub(r'(w+)(W+)(w+)(W+)(w+)',r'52341','alex-love: SB'))
    print(re.sub(r'^al',r'AAAAAAAAA','alex-love: SB alex'))
    
    SB-love: alex
    AAAAAAAAAex-love: SB alex

    5、正则表达式重用

    print(re.findall('^alex','alex say hello alex'))
    print(re.search('^alex','alex say hello alex'))
    
    obj=re.compile(r'^alex')
    print(obj.findall('alex say hello alex'))
    print(obj.search('alex say hello alex').group())

    6、补充:

    print(re.findall(r'<.*?>.*?</.*?>','<h1>hello</h1>'))
    print(re.findall(r'<(.*?)>.*?</(.*?)>','<h1>hello</h1>'))
    print(re.findall(r'<(.*?)>.*?</(1)>','<h1>hello</h1>'))
    print(re.findall(r'<(?P<k>.*?)>.*?</(?P=k)>','<h1>hello</h1>'))
    
    ['<h1>hello</h1>']
    [('h1', 'h1')]
    [('h1', 'h1')]
    ['h1']
    
    取所有
    取分组
    同上
    取k

    7、取数字

    print(re.findall('-?d+.?d*',"1-12*(60+(-40.35/5)-(-4*3))"))
    
    ['1', '-12', '60', '-40.35', '5', '-4', '3']
    print(re.findall('-?d+',"1-12*(60+(-40.35/5)-(-4*3))"))
    print(re.findall('-?d+.d+',"1-12*(60+(-40.35/5)-(-4*3))"))
    
    print(re.findall('-?d+.d+|(-?d+)',"1-12*(60+(-40.35/5)-(-4*3))"))   #只留下整数
    print(re.findall('(-?d+.d+)|-?d+',"1-12*(60+(-40.35/5)-(-4*3))"))    #只留下小数
    expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
    
    print(re.search(r'(([-+*/]?d+.?d*)+)',expression).group())  #取第一个括号内容
    print(eval(expression))   牛逼

    作者:大雄猫
    出处:http://www.cnblogs.com/guoxiangqian/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面 明显位M给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    centos 搭建git 服务器
    easyui Tree树形控件的异步加载
    iis7 部署 mvc4项目提示404错误
    CS0012: 类型“System.Data.Objects.DataClasses.EntityObject”在未被引用的程序集中定义
    asp.net mvc 自定义身份验证
    asp.net mvc 自定义身份验证 2
    爬取五八同城上房子信息并保存到Excel
    scrapy爬取图片并自定义图片名字
    Scrapy爬取到的中文数据乱码问题处理
    scrapy图片-爬取哈利波特壁纸
  • 原文地址:https://www.cnblogs.com/guoxiangqian/p/7746339.html
Copyright © 2020-2023  润新知