zoukankan      html  css  js  c++  java
  • python学习-53 正则表达式

     

    正则表达式

         就其本质而言,正则表达式是一种小型的/高度专业化的编程语言,它内嵌在python中,并通过RE模块实现,正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。

    1.元字符

    -普通字符,大多数字符和字母都会和自身匹配

    -元字符

     例如: .   ^   $   *   ?   { }   [  ]   |   ( ) 

    >>> re.findall("a...d","abcfdasf")
    ['abcfd']
    >>> re.findall("^a...d","abcfdasf")       # 需要找的内容必须在字符串开头
    ['abcfd']
    >>> re.findall("x.....u$","xiaohongxiaogangxiaomingxiaowangxiaoliu")        # 需要找的内容必须在结尾
    ['xiaoliu']
    >>> re.findall("xiaoliux+","xiaohongxiaogangxiaomingxiaowangxiaoliu")  # + (1,无穷)
    []
    >>> re.findall("xiaoliux*","xiaohongxiaogangxiaomingxiaowangxiaoliu")  # * (0,无穷)
    ['xiaoliu']
    >>> 
    >>> re.findall("liu?","xiaohongxiaogangxiaomingxiaowangxiaoliuuu")    # ? (0,1)
    ['liu']
    >>> re.findall("liu{3}","xiaohongxiaogangxiaomingxiaowangxiaoliuuu")       # { } 可以是任意范围
    ['liuuu'] 
    >>> re.findall("liu{4}","xiaohongxiaogangxiaomingxiaowangxiaoliuuu")
    []

    >>> re.findall ("q[a-z]","sdafqaa")    # q与取到的a到z相匹配
    ['qa']

    >>> re.findall ("q[0-9]*","sdafq77aa456")  # 取数字
    ['q77']
    >>> re.findall ("q[^a-z]","sdafq77aa456")    #  ^ 匹配 非 a-z的值
    ['q7']
    >>> re.findall ("([^()]*)","12+(34*6+2-5*(2-1))")  #  ( 将括号转换为普通括号
    ['(2-1)']

    -------

    d 匹配任何十进制数,它相当于类[0-9]

    D 匹配任何非数字字符串,它相当于类[^0-9]

    s匹配任何空白字符,它相当于类[ f v]

    S 匹配任何非空白字符,它相当于类[^ f v]

    w 匹配任何字母数字字符,它相当于类[a-zA-Z0-9]

    W 匹配任何非字母数字字符,它相当于类[^ a-zA-Z0-9]

     匹配一个特殊字符边界,比如空格,& ,#等

    >>> re.findall ("d+","12+(34*6+2-5*(2-1))")
    ['12', '34', '6', '2', '5', '2', '1']
    >>> re.findall ("D+","12+(34*6+2-5*(2-1))")
    ['+(', '*', '+', '-', '*(', '-', '))']
    >>> re.findall ("s","hello world")
    [' ']
    >>> re.findall ("S","hello world")
    ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
    >>> re.findall ("w+","hello world")
    ['hello', 'world']
    >>> re.findall ("W","hello world")
    [' ']
    >>> re.findall ("w","hello1 world2")
    ['h', 'e', 'l', 'l', 'o', '1', 'w', 'o', 'r', 'l', 'd', '2']
    >>> re.findall ("w+","hello1 world2")
    ['hello1', 'world2']
  • 相关阅读:
    [已解决]报错:报错AttributeError: 'int' object has no attribute 'upper'
    Pandas之read_excel()和to_excel()函数解析
    [已解决]报错This event loop is already running
    [转]NMON服务器监控、指标说明
    LoadRunner编程之跳出迭代
    sqlplus与shell互相传值的几种情况
    Loadrunner中socket协议中的三个关联函数
    ORACLE expdp/impdp导出实例
    Linux下的split 命令(将一个大文件根据行数平均分成若干个小文件)
    批量快速的导入导出Oracle的数据(spool缓冲池、java实现)
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11336850.html
Copyright © 2011-2022 走看看