对 url 路由脚本中正则表达式的行为感到困惑

发布于 2024-11-29 03:48:03 字数 359 浏览 0 评论 0原文

我刚刚学习完正则表达式,我认为我应该将它放入有用的东西中,因此我使用 php 和以下正则表达式创建了一个小 url 路由脚本:

^(?:/(\w+)?)*$

(php 代码当前不执行任何操作,只是打印出 preg_match 中的匹配组) 目前,如果给定 url /foobar/foo/bar,匹配组是整个字符串(正常行为)和 url 的最后部分(在本例中:bar ).
显然,这是一个问题。

我认为这是因为使用了 1 个捕获组造成的,它只捕获最后一个匹配的字符串,但我不确定。任何有关其真正原因和/或解决方案的建议将不胜感激。

提前致谢!

I just finished learning about regex and I thought that I should put it into something useful, so I created a small url routing script with php and the following regex:

^(?:/(\w+)?)*$

(the php code currently doesnt do anything, just prints out the matching groups from preg_match)
currently if given the url /foobar/foo/bar, the matching groups are the entire string (normal behavior) and the last part of the url (in this case: bar).
Obviously, this is a problem.

I think that this is caused because of the use of 1 capture group, which only captures the last matching string, but I'm not sure. any advice on the real cause of this and/or a solution to this will be greatly appreciated.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人生戏 2024-12-06 03:48:03

您已经正确诊断了问题 - 在每次重复周围组时,捕获组先前匹配的内容都会被新匹配的“覆盖”。

目前还不太清楚您期望发生什么。我想您会希望路径的每个部分都作为自己的组“被记住”?这是 PHP 中无法对重复组执行的操作(只有少数正则表达式方言(Perl 6 和 .NET)允许这样的操作)。

在您的情况下,您可能最好使用正则表达式来验证 URL,然后沿斜杠将其拆分:

$result = preg_split('%/%', $subject);

You have diagnosed the problem correctly - on each repetition of the surrounding group, the previously matched contents of the capturing group are "overwritten" by the new match.

It's not quite clear what you would have expected to happen. I guess that you would have liked each part of the path to be "remembered" as its own group? This is something you can't do with repeated groups in PHP (only a few regex dialects (Perl 6 and .NET) allow something like this).

In your case, you're probably better off by using your regex to validate the URL and then split it along the slashes:

$result = preg_split('%/%', $subject);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文