zoukankan      html  css  js  c++  java
  • python正则表达式(三)

    表示边界

    示例1:$

    需求:匹配163.com的邮箱地址

    #coding=utf-8
    
    import re
    
    # 正确的地址
    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.com$", "xiaoWang@163.comheihei")
    ret.group()

    示例2: 

    >>> 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'
    
    >>> re.match(r".*ver", "hover abc").group()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'group'

    示例3:B

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

    匹配分组

    示例1:|

    需求:匹配出0-100之间的数字

    #coding=utf-8
    
    import re
    
    ret = re.match("[1-9]?d","8")
    ret.group()
    
    ret = re.match("[1-9]?d","78")
    ret.group()
    
    # 不正确的情况
    ret = re.match("[1-9]?d","08")
    ret.group()
    
    # 修正之后的
    ret = re.match("[1-9]?d$","08")
    ret.group()
    
    # 添加|
    ret = re.match("[1-9]?d$|100","8")
    ret.group()
    
    ret = re.match("[1-9]?d$|100","78")
    ret.group()
    
    ret = re.match("[1-9]?d$|100","08")
    ret.group()
    
    ret = re.match("[1-9]?d$|100","100")
    ret.group()

    示例2:( )

    需求:匹配出163、126、qq邮箱之间的数字

    #coding=utf-8
    
    import re
    
    ret = re.match("w{4,20}@163.com", "test@163.com")
    ret.group()
    
    ret = re.match("w{4,20}@(163|126|qq).com", "test@126.com")
    ret.group()
    
    ret = re.match("w{4,20}@(163|126|qq).com", "test@qq.com")
    ret.group()
    
    ret = re.match("w{4,20}@(163|126|qq).com", "test@gmail.com")
    ret.group()

  • 相关阅读:
    Codeforces Round #271 (Div. 2) F. Ant colony 线段树
    poj 1744 tree 树分治
    HDU Shell Necklace CDQ分治+FFT
    BZOJ 1567: [JSOI2008]Blue Mary的战役地图 矩阵二维hash
    BZOJ 1042: [HAOI2008]硬币购物 容斥+背包
    HDU 6078 Wavel Sequence 树状数组优化DP
    Gym
    HDU 6058 Kanade's sum 二分,链表
    HDU 6061 RXD and functions NTT
    ZOJ 3233 Lucky Number 容斥原理
  • 原文地址:https://www.cnblogs.com/leecoffee/p/9034411.html
Copyright © 2011-2022 走看看