• python 正则


    1.正则有三种匹配方法

    import re
    re.match #从开始位置开始匹配,如果开头没有则无
    
    re.search #搜索整个字符串
    
    re.findall #搜索整个字符串,返回一个list

    2.'|'  或规则

    import re
    
    s = 'I have a dog , I have a cat ,I have a dog'
    r = re.findall(r'I have a (dog|cat)',s)
    for i in r:print i
    '''
    dog
    cat
    dog
    [Finished in 0.2s]
    '''
    r = re.findall(r'I have a (?:dog|cat)',s)
    for i in r:print i
    '''
    I have a dog
    I have a cat
    I have a dog
    [Finished in 0.2s]
    '''

     --------实例------------

    import re
    
    data = '''<div class="ntes-nav-select-pop">
    <ul class="ntes-nav-select-list clearfix">
    <li data-module-name="n_topnavapplist_t_0">
    <a href="http://m.163.com/newsapp/#f=topnav"><span><em class="ntes-nav-app-newsapp">网易新闻</em></span></a>'''
    
    r = re.findall(r'(?:class=".+?"|href=".+?")',data)
    for i in r:print i
    '''
    class="ntes-nav-select-pop"
    class="ntes-nav-select-list clearfix"
    href="http://m.163.com/newsapp/#f=topnav"
    '''
  • 相关阅读:
    MiniOS系统
    《硅谷传奇》
    《构建之法》1—3章
    学术诚信与职业道德
    Sprint2
    Scrum 项目 7.0 Sprint回顾
    Scrum 项目 6.0 sprint演示
    Scrum 项目 5.0
    Scrum 项目4.0
    操作系统 实验三 进程调度模拟程序
  • 原文地址:https://www.cnblogs.com/alamZ/p/7048448.html
Copyright © 2020-2023  润新知