[英]Weird regex bug in iis url-rewrite
这是我的模式:
^(\w{2}-\w{2})/questions(?:/(\w+))?(?:/(\d+))?(?:/.*?)?$
这些是我正在测试的内容:
en-us/questions/ask
en-us/questions/newest/15
en-us/questions/12/just-a-text-to-be-ignored
它完美运行,这是演示:
https://regex101.com/r/yC3tI8/1
但以下重写规则:
<rule name="en-us questions" enabled="true" stopProcessing="true">
<match url="^(\w{2}-\w{2})/questions(?:/(\w+))?(?:/(\d+))?(?:/.*?)?$" />
<action type="Rewrite" url="/questions.aspx?lang={R:1}&tab={R:2}&pid={R:3}" />
</rule>
当我将链接en-us/questions/newest
重定向到: /questions.aspx?lang=en-us&tab=&pid=
en-us/questions/newest
/questions.aspx?lang=en-us&tab=&pid=
这有什么问题? 现在大约 5 个小时,我只是在回顾同样的事情
由于您有三种不同的可能 url 结尾,最终会影响重写 url 的结果,您可以设置一个全包规则,希望能匹配您想要的所有内容,或者您可以设置三个规则来相应地处理每个:
一条规则:
^(\w{2}-\w{2})/questions/(\w+)/?(\d+)?.*$
https://regex101.com/r/dN8bM9/1 - 尝试处理所有情况
<rule name="en-us questions" enabled="true" stopProcessing="true">
<match url="^(\w{2}-\w{2})/questions/(\w+)/?(\d+)?.*$" />
<action type="Rewrite" url="/questions.aspx?lang={R:1}&tab={R:2}&pid={R:3}" />
</rule>
* 注意:原始模式未能捕获第二组的一个可能原因是包含(?:)
- 这意味着匹配但不捕获; 忽略这一点可能会解决那里的大部分问题。
三个规则:
^(\w{2}-\w{2})/questions/(\w+)$
https://regex101.com/r/lI8bQ1/1 - en-us/questions/[单字]
^(\w{2}-\w{2})/questions/(\d+)/.*$
https://regex101.com/r/hV5fK3/1 - en-us/questions/[digits]/discard
^(\w{2}-\w{2})/questions/(\w+)/(\d+)$
https://regex101.com/r/kO0dJ0/1 - en-us/questions/[单字]/[数字]
将所有这些放在一个规则集中:
<rule name="en-us questions case one" enabled="true" stopProcessing="true">
<match url="^(\w{2}-\w{2})/questions/(\w+)$" />
<action type="Rewrite" url="/questions.aspx?lang={R:1}&tab={R:2}" />
</rule>
<rule name="en-us questions case two" enabled="true" stopProcessing="true">
<match url="^(\w{2}-\w{2})/questions/(\d+)/.*$" />
<action type="Rewrite" url="/questions.aspx?lang={R:1}&tab={R:2}" />
</rule>
<rule name="en-us questions case three" enabled="true" stopProcessing="true">
<match url="^(\w{2}-\w{2})/questions/(\w+)/(\d+)$" />
<action type="Rewrite" url="/questions.aspx?lang={R:1}&tab={R:2}&pid={R:3}" />
</rule>
* 注意:您可能需要以某种方式进行调整,但它应该让您了解如何适应三种不同的变体(如您所见)以重写您的网址。
请注意,您有三个懒惰的捕获:
(?:/(\\w+))?
(?:/(\\d+))?
(?:/.*?)?
asp.net 的正则表达式实现解释?
作为:
除了指定给定模式可能恰好出现 0 次或 1 次之外,
?
当它可能匹配输入字符串中的多个字符时,字符还会强制模式或子模式匹配最少数量的字符。
因此,asp.net 没有将字符分配给1 ,没有字符分配给2 ,并收集其余的字符3 。
使用贪婪匹配而不是惰性匹配?
强制使用: {0,1}
所以你的正则表达式应该是这样的:
^(\w{2}-\w{2})/questions(?:/(\w+)){0,1}(?:/(\d+)){0,1}(?:/.*?)?$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.