zoukankan      html  css  js  c++  java
  • 【python cookbook】【字符串与文本】7.定义实现最短匹配的正则表达式

    问题:使用正则表达式对文本模式匹配,将识别出来的最长的可能匹配修改为找出最短的可能匹配

    解决方法:在匹配模式中的*操作符后加上?修饰符

    import re
    
    # Sample text
    text = 'Computer says "no." Phone says "yes."'
    
    # (a) Regex that finds quoted strings - longest match
    str_pat = re.compile(r'"(.*)"')
    print(str_pat.findall(text))
    
    # (b) Regex that finds quoted strings - shortest match
    str_pat = re.compile(r'"(.*?)"')
    print(str_pat.findall(text))
    >>> ================================ RESTART ================================
    >>> 
    ['no." Phone says "yes.']
    ['no.', 'yes.']
    >>> 

    (a)例子中被错误的匹配成2个被引号包围的字符串

    补充:本节提到了一个当编写含有句点(.)字符的正则表达式时会遇到的问题。

    在模式匹配中,句点除了换行符之外可匹配任意字符。

  • 相关阅读:
    SQL SERVER开窗函数
    SQL SERVER调优常用方法
    SQL SERVER其它函数
    SQL SERVER时间函数
    SQL SERVER字符串函数
    ptyhon技能树及其学习资源
    机器学习中的数学基础
    python-spider 第10题
    python-spider 第七关
    python-spider 第六关
  • 原文地址:https://www.cnblogs.com/apple2016/p/5790837.html
Copyright © 2011-2022 走看看