zoukankan      html  css  js  c++  java
  • Python的re应用

     re的效果:

    re.match是用来进行正则匹配检查的方法,若字符串匹配正则表达式,则match方法返回匹配对象(Match Object),否则返回None(注意不是空字符串"")。
    匹配对象Macth Object具有group方法,用来返回字符串的匹配部分。

    1单字符匹配

    ret = re.match("嫦娥d号","嫦娥3号发射成功")
    print ret.group()

    2.原生字符串

    Python中字符串前面加上 r 表示原生字符串

    3.表示数量

    4.边界

    163邮箱地址匹配
    ret = re.match("[w]{4,20}@163.com", "xiaoWang@163.com")
    ret.group()
    ret = re.match("[w]{4,20}@163.com$", "xiaoWang@163.comheihei")
    ret.group()

      ret = re.match("w{4,20}@(163|126|qq).com", "test@gmail.com")

      ret.group()

    
    

     

     

    边界匹配
    >>> re.match(r".*ver", "ho ver abc").group()
    'ho ver'
    >>> re.match(r".*ver", "ho verabc").group()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'group'

    5.匹配分组

    6.高级用法

    import re
    ret = re.search(r"d+", "阅读次数为 9999")
    ret.group()
    
    ret = re.findall(r"d+", "python = 9999, c = 7890, c++ = 12345")
    print ret
    
    匹配替换
    ret = re.sub(r"d+", '998', "python = 997")
    print ret
    
    匹配切割
    ret = re.split(r":| ","info:xiaoZhang 33 shandong")
    print ret

    7.贪婪与非贪婪

    在"*","?","+","{m,n}"后面加上?,使贪婪变成非贪婪

  • 相关阅读:
    算法设计--求连续子向量的最大和问题--论想法思路的重要性
    --a和a--
    程序员一个知道的一些法则
    django admin
    Python递归
    Python内置函数
    Python协程函数
    Python 生成器
    Python迭代器
    Python装饰器
  • 原文地址:https://www.cnblogs.com/topass123/p/12965418.html
Copyright © 2011-2022 走看看