zoukankan      html  css  js  c++  java
  • python正则中的贪婪与非贪婪

    当重复一个正则表达式时,如用 a*,操作结果是尽可能多地匹配模式。当你试着匹配一对对称的定界符,如 HTML 标志中的尖括号。匹配单个 HTML 标志的模式不能正常工作,因为 .* 的本质是“贪婪”的

    >>> s = '<html><head><title>Title</title>'
    >>> len(s)
    32
    >>> print re.match('<.*>', s).span()
    (0, 32)
    >>> print re.match('<.*>', s).group()
    <html><head><title>Title</title>
    RE 在 "<html>" 中 匹配 "<",.* 会消耗掉字符串的剩余部分。RE 中保持更多的向左匹配, 不能在字符串结尾匹配“>”,因此正则表达式必须一个字符一个字符地回溯,直到它找到 > 的匹配。最终的匹配从 "<html" 中的 "<" 到 "</title>" 中的 ">",这变成了全文匹配,并不是你想要的结果。

    在这种情况下,解决方案是使用不贪婪的限定符 *?、+?、?? 或 {m,n}?,尽可能匹配小的文本。在上面的例子里,在第一个 "<" 之后立即尝试匹配 ">",当它失败时,引擎一次增加一个字符,并在每步重试 匹配">"。这个处理将得到正确的结果:

    >>> print re.match('<.*?>', s).group()
    <html>

    注意一下比较:

    >>> re.findall(r"a(\d+?)""a23b")
            
    ['2']
    >>> 
    re.findall(r"a(\d+)""a23b")
            ['23']

    ---------------比较一下两者的不同------------------------

    >>> re.findall(r"a(\d+)b""a23b")
            
    ['23']
    >>> 
    re.findall(r"a(\d+?)b""a23b")

            
    ['23']

    有时使用贪婪模式匹配网页代码时,会出现卡机情况,比如用这个语句:

    sty_scr_tag = re.compile('(<style.*?[^>]*>.*?([\S\s]+)<\/style>)|(<script.*?[^>]*>.*?<\/script>)|(<script.*?[^>]*>.*?([\S\s]+?)<\/script>)',re.M)
    content = sty_scr_tag.sub('', content)

    去匹配baike.baidu.com这个网页,你会发现编译器一直卡在那里不会动,但当语句变成这个:

    sty_scr_tag = re.compile('(<style.*?[^>]*>.*?<\/style>)|(<script.*?[^>]*>.*?<\/script>)|(<script.*?[^>]*>.*?([\S\s]+?)<\/script>)',re.M)
    content = sty_scr_tag.sub('', content)

    时,就可以了

    python,go,redis,mongodb,.net,C#,F#,服务器架构
  • 相关阅读:
    多线程实现看病Test2
    多线程Test1
    实现注册的账户在重新运行程序后依然可以登录
    教资科一科二pdf资料+科三
    error Custom elements in iteration require 'v-bind:key' directives vue/valid-v-for
    vue-router配置路由出现错误: Mixed spaces and tabs no-mixed-spaces-and-tabs
    [vue-router] route config "component" for path:canot be a string id. Use an actual compone
    20 个超赞的 CSS3 库
    20个简洁的 JS 代码片段
    Vue 前端代码风格指南 |
  • 原文地址:https://www.cnblogs.com/descusr/p/2706766.html
Copyright © 2011-2022 走看看