zoukankan      html  css  js  c++  java
  • 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>'
    每天多一点提高,给自己一些激励,开心生活,用编码来丰富我的生活,加油! ↖(^ω^)↗
  • 相关阅读:
    由PhysicalFileProvider构建的物理文件系统
    Net Core WebApi单元测试
    多个项目使用NET Core
    ReactNative
    定制样式插入到ueditor
    ES6的Class
    Redis存储Session
    二叉 查找树 排序树 搜索树
    SignalR实现实时日志监控
    KNN(k-nearest neighbor的缩写)又叫最近邻算法
  • 原文地址:https://www.cnblogs.com/graceting/p/3631031.html
Copyright © 2011-2022 走看看