zoukankan      html  css  js  c++  java
  • re模块

    1、正则表达式的概念

    正则表达式是用来简洁表达一组字串的表达式。

    正则表达式的语法

    re库的基本使用

    原生字符合以r开头,反指不包含转义符的字符串

    import re
    
    match1 = re.search(r'[1-9]d{5}', 'BIT 100081')
    if match1:
        print(match1.group(0))  #100081
    
    match2 = re.match(r'[1-9]d{5}', "100081 BIT ")
    if match2:
        print(match2.group(0)) #100081
    
    match3 = re.findall(r'[1-9]d{5}','100081 BIT  BIT 100084')
    print(match3) #['100081', '100084']
    
    s = re.split(r'[1-9]d{5}','BIT100081 BIT100084')
    print(s)#['BIT', ' BIT', '']
    
    s1 = re.split(r'[1-9]d{5}','BIT100081 BIT100084',maxsplit=1)
    print(s1)#['BIT', ' BIT100084']
    
    for i in re.finditer(r'[1-9]d{5}','BIT100081 BIT100084'):
        if i:
            print(i.group(0)) #100081 100084
    
    r = re.sub(r'[1-9]d{5}', ':zcode', 'BIT100081 BIT100084')
    print(r) #BIT:zcode BIT:zcode

    re库的Match对象

    import re
    
    match1 = re.search(r'[1-9]d{5}', 'BIT 100081')
    print(match1.string) #BIT 100081
    print(match1.re) #re.compile('[1-9]\d{5}')
    print(match1.pos) #0
    print(match1.endpos) #10
    print(match1.group(0)) #100081
    print(match1.start()) #4
    print(match1.end()) #10
    print(match1.span()) #(4, 10)

    re库的贪婪匹配和最小匹配

    re库默认是贪婪匹配,输出匹配到的最长度符串

    import re
    
    match1 = re.search(r'py.*n', 'pyfdjklafjn')
    if match1:
        print(match1.group(0)) #pyfdjklafjn

    如何输出最小度符串

    import re
    
    match1 = re.search(r'py.*?n', 'pyfdjklafjn')
    if match1:
        print(match1.group(0)) #pyfn

  • 相关阅读:
    c语言中 fgetc函数、fputc函数实现文件的复制
    c语言 13-7 利用fgetc函数输出文件的字符数
    c语言 13-6 利用fgetc函数输出文件的行数
    c语言中fgetc函数:显示文件内容
    c语言 13-5
    c语言 获取程序上一次运行时间的程序
    hzwer模拟赛 虫洞
    LYDSY热身赛 escape
    bzoj2330 糖果
    繁华模拟赛 Vicent坐电梯
  • 原文地址:https://www.cnblogs.com/jp-mao/p/6702019.html
Copyright © 2011-2022 走看看