正则表达式的奇怪行为 (?:)
strange behavior of regex (?:)
在下面的亲戚中 url 我想获得可选的 origin 参数,但我只需要 origin 本身(在下面的 [=46] 中就是 test =] 不是 with-test-origin)
/somequery/with-test-origin/param/param/more
当我使用这个正则表达式时 url 匹配:
([^/]+)/(?:(?:with-)([^/]*)(-origin)/)?([^/]*/)?([^/]*/)?more
但我用这个的时候不是:
([^/]+)/(?:(?:with-)([^/]*)(?:-origin)/)?([^/]*/)?([^/]*/)?more
有什么问题?为什么当我不想赶上 (-origin) 组时它不起作用?
编辑:
我在一个应用程序中测试它运行良好。我也在 web.config:
中尝试过这个
([^/]+)/(?:(with-)([^/]*)(?:-origin)/)?([^/]*/)?([^/]*/)?more
in web.config(从 (?:with-) 中删除了 ?: 并将其放回 (?:-origin) 并且它在 web.config 也是。web.config 文件中是否有关于组数或我不想捕获的组数的限制?
这就是我在 web.config 文件中使用它的方式:
<rule name="tst" enabled="true" stopProcessing="true">
<match url="([^/]+)/(?:(?:with-)([^/]*)(?:-origin)/)?([^/]*/)?([^/]*/)?more" />
<action type="Rewrite" url="moreinfo.aspx?cat={R:1}&sub1={R:2}&sub2={R:3}&sub3={R:4}&sub4={R:5}" />
</rule>
匹配行为不应根据此差异进行更改。问题是:
- 您的 web.config 文件中的其他内容。
- 正则表达式引擎中的错误或 web.config。
经过几个小时的努力,我终于找到了问题。
匹配是从零开始的,就像 {R:0} {R:1} ,...
当使用 ?: 时,匹配数减少了 1,例如 {R:1} 在添加 ?: 之前有效无效。
在下面的亲戚中 url 我想获得可选的 origin 参数,但我只需要 origin 本身(在下面的 [=46] 中就是 test =] 不是 with-test-origin)
/somequery/with-test-origin/param/param/more
当我使用这个正则表达式时 url 匹配:
([^/]+)/(?:(?:with-)([^/]*)(-origin)/)?([^/]*/)?([^/]*/)?more
但我用这个的时候不是:
([^/]+)/(?:(?:with-)([^/]*)(?:-origin)/)?([^/]*/)?([^/]*/)?more
有什么问题?为什么当我不想赶上 (-origin) 组时它不起作用?
编辑:
我在一个应用程序中测试它运行良好。我也在 web.config:
中尝试过这个([^/]+)/(?:(with-)([^/]*)(?:-origin)/)?([^/]*/)?([^/]*/)?more
in web.config(从 (?:with-) 中删除了 ?: 并将其放回 (?:-origin) 并且它在 web.config 也是。web.config 文件中是否有关于组数或我不想捕获的组数的限制?
这就是我在 web.config 文件中使用它的方式:
<rule name="tst" enabled="true" stopProcessing="true">
<match url="([^/]+)/(?:(?:with-)([^/]*)(?:-origin)/)?([^/]*/)?([^/]*/)?more" />
<action type="Rewrite" url="moreinfo.aspx?cat={R:1}&sub1={R:2}&sub2={R:3}&sub3={R:4}&sub4={R:5}" />
</rule>
匹配行为不应根据此差异进行更改。问题是:
- 您的 web.config 文件中的其他内容。
- 正则表达式引擎中的错误或 web.config。
经过几个小时的努力,我终于找到了问题。
匹配是从零开始的,就像 {R:0} {R:1} ,... 当使用 ?: 时,匹配数减少了 1,例如 {R:1} 在添加 ?: 之前有效无效。