gpt4 book ai didi

正则表达式不够贪婪

转载 作者:行者123 更新时间:2023-12-01 09:09:19 25 4
gpt4 key购买 nike

我有以下正则表达式,它在出现新情况之前运行良好

^.*[?&]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>.*)$

最佳答案

问题

问题不在于 .* 不够贪心;就是前面出现的other .*也是也是贪心的。

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

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

这里我们有两个捕获组。 \1 捕获 [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 不情愿,所以 5 实际上是由 \2 来获取的。

附件

相关问题


修复

因此,将此应用于您的问题,有两种方法可以解决此问题:您可以让第一个 .* 不情愿,所以 (see on rubular.com):

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

或者你可以完全去掉前缀匹配部分(see on rubular.com):

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

关于正则表达式不够贪婪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3045946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com