zoukankan      html  css  js  c++  java
  • python 贪婪和非贪婪模式

    这样的正则表达式:

    r'*(.+)*'  如果想要匹配*something*这样的一个串按道理说是没问题的

    但是如果文本是*this* is *something*

    那么我们的正则表达式就会采取贪婪模式匹配第一个* 最后一个*

    而中间的 两个*就当作是第一个分组里面的内容了

    要想采取非贪婪模式 就只需在其后面加一个问号r'*(.+?)*'

    s1='hello,*something!*
    
    pattern1=re.compile('*(.+)*')
    print re.sub(pattern1,r'<em>1</em>',s1)
    ##输出结果hello,<em>something</em>
    #############################################


    s = '*hello* is *something*'

    pattern =re.compile(r'*(.+)*')
    print re.sub(pattern, r'<em>1<em>', s)

    #输出结果
    <em>hello* is *something<em>
    #############################################
    s = '*hello* is *something*'

    pattern =re.compile(r'*(.+?)*')
    print re.sub(pattern, r'<em>1<em>', s)

    #输出结果<em>hello<em> is <em>something<em>

      

  • 相关阅读:
    闰年测试
    EditBox的测试用例设计
    测试工程中的评审
    测试框架
    github
    第一次上机实验
    对软件测试的初步认识
    白盒测试
    Date : 日期对象
    C++ 格式化输出 及 输入 流
  • 原文地址:https://www.cnblogs.com/ldphoebe/p/5564569.html
Copyright © 2011-2022 走看看