代码之家  ›  专栏  ›  技术社区  ›  CaffGeek

正则表达式不够贪婪

  •  3
  • CaffGeek  · 技术社区  · 15 年前

    我有下面的正则表达式,在出现新情况之前它一直工作得很好

    ^.*[?&]U(?:RL)?=(?<URL>.*)$
    

    基本上,它是针对URL使用的,用于获取U=,或URL=之后的所有内容,并在URL匹配中返回它

    http://localhost?a=b&u=http://otherhost?foo=bar

    网址= http://otherhost?foo=bar

    http://localhost?a=b&u=http://otherhost?foo=bar&url=http://someotherhost

    理想情况下,我希望URL是“ http://otherhost?foo=bar&url=http://someotherhost 相反,它只是 http://someotherhost "

    编辑:我想这把它修好了…虽然不好看

    ^.*[?&](?<![?&]U(?:RL)?=.*)U(?:RL)?=(?<URL>.*)$
    
    1 回复  |  直到 13 年前
        1
  •  9
  •   Community CDub    8 年前

    问题

    问题不在于 .* 是不够贪婪;是因为 其他 .* 前面出现的是 贪婪的。

    为了说明这个问题,让我们考虑一个不同的例子。考虑以下两种模式;他们是一样的,只是不愿意 \1 在第二种模式中:

                  \1 greedy, \2 greedy         \1 reluctant, \2 greedy
                  ^([0-5]*)([5-9]*)$           ^([0-5]*?)([5-9]*)$
    

    这里我们有两个抓捕小组。 捕获 [0-5]* ,和 \2 [5-9]* . 下面是这些模式匹配和捕获的并排比较:

                  \1 greedy, \2 greedy          \1 reluctant, \2 greedy
                  ^([0-5]*)([5-9]*)$            ^([0-5]*?)([5-9]*)$
    Input         Group 1    Group 2            Group 1    Group 2
    54321098765   543210     98765              543210     98765
    007           00         7                  00         7
    0123456789    012345     6789               01234      56789
    0506          050        6                  050        6
    555           555        <empty>            <empty>    555
    5550555       5550555    <empty>            5550       555
    

    \2 \1 还没抢到第一个!因此,如果你想 \2 5 \1 不情愿,所以 实际上是为了抢先一步 \2

    附件

    相关问题


    修复

    .* 不情愿,所以( see on rubular.com

    ^.*?[?&]U(?:RL)?=(?<URL>.*)$
    

    see on rubular.com ):

    [?&]U(?:RL)?=(?<URL>.*)$