zoukankan      html  css  js  c++  java
  • 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"
    '''
  • 相关阅读:
    python 数据类型
    python核心语法
    python 基础知识
    format 用法
    有关python 函数参数
    模拟,队列与堆栈
    字符编码
    [LeetCode] Set Matrix Zeroes
    [LeetCode] Rotate Image
    [LeetCode] Unique Paths
  • 原文地址:https://www.cnblogs.com/alamZ/p/7048448.html
Copyright © 2011-2022 走看看