• python_re函数


    1,贪婪和非贪婪模式

    重复运算符默认是贪婪的,即会进行尽可能多的匹配

    代码示例:

    >>> import re
    >>> emphasis_pattern = re.compile(r'''
    *          #beginning emphais tag --an asterisk
    (           #begin group for capturing phrase
    [^*]+      #capture anything except asterisks
    )           #end group
    *          #ending emphasis tag
    ''', re.VERBOSE)
    >>> re.sub(emphasis_pattern, r'<em>1</em>', 'Hello,*world*!')
    'Hello,<em>world</em>!'
    >>> emphasis_pattern= r'*(.+)*'
    >>> re.sub(emphasis_pattern, r'<em>1</em>', '*This* is *a boy!*')
    '<em>This* is *a boy!</em>'

    ##让正则表达式变的更加易读的方式是在re函数中使用VERBOSE标志,这样可在模式中添加空白

    ##使用compile函数处理了正则表达式,让处理过程更有效率,将正则表达式转换为模式对象

    将贪婪模式变换为非贪婪模式:只需要在重复运算符后面加上一个问号即可

    代码示例:

    >>> emphasis_pattern= r'*(.+?)*'
    >>> re.sub(emphasis_pattern, r'<em>1</em>', '*This* is *a boy!*')
    '<em>This</em> is <em>a boy!</em>'
    每天多一点提高,给自己一些激励,开心生活,用编码来丰富我的生活,加油! ↖(^ω^)↗
  • 相关阅读:
    mysql 百万级查询优化
    hibernate N+1
    sql 技巧
    redis做成windows服务
    jsonp 跨域
    maven+spring-data-jpa环境搭建
    通过浏览器地址进行 post get 请求
    spring-data-jpa 新增 修改 删除 查询 分页
    mybatis+springMVC
    java 基于 bootstrap_datagrid 分页
  • 原文地址:https://www.cnblogs.com/graceting/p/3631031.html
Copyright © 2020-2023  润新知