zoukankan      html  css  js  c++  java
  • Python3正则表示式(3)

    正则表示式对象

    对象1:

    案例1:

    import re 
    example = 'ShanDong Institute of Business and Technology'
    pattern = re.compile(r'Bw+')  # 查找以B开头的单词
    pattern.findall(example)
    # 结果:['Business']
    pattern = re.compile(r'w+g')  # 查找以字母g结尾的单词
    pattern.findall(example)
    # 结果:['ShanDong']
    pattern = re.compile(r'[a-zA-Z]{3}')  # 查找3个字母长的单词
    pattern.findall(example)
    # 结果:['and']
    pattern.search(example)
    # 结果:<_sre.SRE_Match object; span=(31, 34), match='and'>
    pattern = re.compile(r'w*aw*') # 查找所有含字母a的单词
    pattern.findall(example)
    # 结果:['ShanDong', 'and']
    
    text = 'He was carefully disguised but captured quickly by police.'
    re.findall(r'w+ly', text)  # 查找所有以字母组合ly结尾的单词
    # 结果:['carefully', 'quickly']

    对象2

    案例2:

    example = """Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts."""
    
    pattern = re.compile(r'bw*', re.I)
    print(pattern.sub('*', example))
    # 结果
    '''
    * is * than ugly.
    Explicit is * than implicit.
    Simple is * than complex.
    Complex is * than complicated.
    Flat is * than nested.
    Sparse is * than dense.
    Readability counts.
    '''
    print(pattern.sub(lambda x: x.group(0).upper(), example))
    # 结果
    '''
    BEAUTIFUL is BETTER than ugly.
    Explicit is BETTER than implicit.
    Simple is BETTER than complex.
    Complex is BETTER than complicated.
    Flat is BETTER than nested.
    Sparse is BETTER than dense.
    Readability counts.
    '''
    print(pattern.sub('#', example, 1))
    # 结果
    '''
    # is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    '''

    对象3


    知识在于点点滴滴的积累,我会在这个路上Go ahead,
    有幸看到我博客的朋友们,若能学到知识,请多多关注以及讨论,让我们共同进步,扬帆起航。

    后记:打油诗一首

    适度锻炼,量化指标

    考量天气,设定目标

    科学锻炼,成就体标

    高效科研,实现学标


     

  • 相关阅读:
    D. Longest Subsequence
    线段树入门HDU_1754
    poj_2503(map映射)
    HDU_4826
    poj_2251
    day 44 单表查询,多表查询
    day43 字段的修改、添加和删除,多表关系(外键),单表详细操作(增删改查)
    day 42 数据库的配置、数据库与表的一些剩余操作、用户操作、数据库表的引擎、数据库的模式、mysql支持的数据类型、约束
    day41 数据库介绍、数据库基本操作
    day 40 线程队列、线程定时器、进程池和线程池、同步与异步、用多线程来写socket服务端与客户端
  • 原文地址:https://www.cnblogs.com/brightyuxl/p/9237318.html
Copyright © 2011-2022 走看看