zoukankan      html  css  js  c++  java
  • python正则表达式re.match以及re.search函数

    re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

    例子1:

    #!/usr/bin/python

    import re

    print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配  #过滤掉一些信息,只留位置,返回元组

    print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配

    结果为:

    (0,3)

     None

    例子2:

    #!/usr/bin/python3 

    import re

    line = "Cats are smarter than dogs" # .* 表示任意匹配除换行符( 、 )之外的任何单个或多个字符

    matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

    if matchObj:

    print ("matchObj.group() : ", matchObj.group())

    print ("matchObj.group(1) : ", matchObj.group(1))

    print ("matchObj.group(2) : ", matchObj.group(2))

    else: print ("No match!!")

    以上实例执行结果如下:

    matchObj.group() : Cats are smarter than dogs
    matchObj.group(1) : Cats
    matchObj.group(2) : smarter

    re.search 扫描整个字符串并返回第一个成功的匹配。

    #!/usr/bin/python3
    import re
    print(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配
    print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配

    结果为:

    (0, 3)
    (11, 14)



    
    
  • 相关阅读:
    设计模式
    IPC- Posix与system v
    squashfs文件系统
    各种根文件系统
    SPI通讯协议
    tty各种设备的情况
    Linux系统调用过程
    uImage和zImage的区别
    jquery可见性选择器(匹配匹配所有显示的元素)
    jquery可见性选择器(匹配所有隐藏的元素)
  • 原文地址:https://www.cnblogs.com/wangnengwu/p/12416461.html
Copyright © 2011-2022 走看看