• re 库


    正则表达式(regex): 用来简洁表达一组字符的表达式

    通用的字符串框架

    简洁表达一组字符串的表达式

    针对字符串表达“简洁” 和 “特征” 思想的工具

    某字符串的特征归属

    在文本中十分常用

    字符串匹配

    编译:将符合正则表达式语法的字符串转换成正则表达式特征。

    Re库为python的标准库。

    raw string 类型(原生字符串类型,指不包含转义字符) r'text'

    string 类型 if you want to use \, then you have to \

    函数式用法:(6种)

    re.search()

    re.match()

    re.findall()

    re.split()

    re.finditer()

    re.sub()

    import re
    
    '''return match object'''
    match = re.search(r'[0-9]d{5}', 'BIT 100081')
    if match:
        match.group(0)
        print(match.group(0))
    
    '''match will search from the string's beginning'''    
    match = re.match(r'[0-9]d{5}', 'BIT 100084')
    if match:
        print(match.group(0))
    
    '''return list'''    
    match = re.findall(r'[0-9]d{5}', 'BIT 100083 100085')
    print(match)
    
    '''return list'''
    match = re.split(r'[0-9]d{5}', 'BIT 100083 100085', maxsplit=1)
    print(match)
    
    '''return match object'''
    match = re.finditer(r'[0-9]d{5}', 'BIT 100083 100085')
    for ma in match:
        print(ma.group(0))
    
    '''return replaced string'''    
    match = re.sub(r'[0-9]d{5}', 'zipcode', 'BIT100083 100085', count=2)
    print(match)
    View Code

    runfile('F:/Project/study/untitled0.py', wdir='F:/Project/study')
    100081
    ['100083', '100085']
    ['BIT ', ' 100085']
    100083
    100085
    BITzipcode zipcode

    面向对象是用法:(6种)

    regexp = re.compile(pattern, flag=0)

    regexp.search()

    regexp.match()

    regexp.findall()

    regexp.split()

    regexp.finditer()

    regexp.sub()

    返回的match 对象属性和方法:

    m.string

    m.re (带compile)

    m.pos(搜索字符串的起始位置)

    m.endpos

    m.group(0)

    m.start()

    m.end()

    m.span() (start and end relation)

    Re库 默认采用贪婪匹配,即输出匹配最长的匹配。

    match = re.search(r'PY.*N', 'PYANBNCNDN')

    If you want the shortest match, then you should add '?'

    match = re.search(r'PY.*?N', 'PYANBNCNDN')

    *?

    +?

    ??

    {m, n}? 扩展前一个字符m次或n次

     Notes:

  • 相关阅读:
    0528习题 11-15
    通过文档算学生的平均分
    给定两个列表,转换为 DataFrame 类型
    一千美元的故事(钱放入信封中)
    pandas 几个重要知识点
    python文件操作
    是否感染病毒
    安装 kreas 2.2.4 版本问题
    小技巧_01
    【Liunx】Linux 系统启动过程
  • 原文地址:https://www.cnblogs.com/jinggo/p/7726247.html
Copyright © 2020-2023  润新知