preg_match_all 匹配太多

发布于 2024-12-13 21:26:26 字数 290 浏览 0 评论 0原文

我不知道要在正则表达式中添加什么以使其仅匹配“精确”模式。 #users/(.+?)/# 与此字符串 users/john/someweirdstuff/ 将匹配。

我得到 'john' 而不是 'john/someweirdstuff' (这是朝着正确方向迈出的一步),但我根本不希望它匹配。因为字符串(应该是 URL)不一样。

所以基本上,我应该在我的 reg exp 后面添加什么来使它说“最后一个斜杠之后不应该有任何内容”

I don't know what to add to my regular expression to make it only match the 'exact' patterns.
#users/(.+?)/# with this string users/john/someweirdstuff/ will be a match.

I am getting 'john' and not 'john/someweirdstuff' (which is a good step in the right direction), but I don't want it to match at all. Because the string (which are supposed to be URLs) aren't the same.

So basically, what do I add behind my reg exp to make it say "there should nothing after the last slash"

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

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

发布评论

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

评论(2

卸妝后依然美 2024-12-20 21:26:26

您应该使用与字符串结尾匹配的$字符。

您还应该避免匹配“任何字符 (.)”,而应该匹配“任何不是斜杠的字符 ([^/])”。如示例所示 注意,

我省略了问号(),本例中的问号将字符匹配从贪婪(尽可能多地匹配)更改为惰性(尽可能少地匹配)。

另请 就像这样:

#users/([^/]+)/$#

You should use the $ character that matches the end of the string.

You should also avoid matching "any character (.)" and you should match "any character which is not a slash ([^/]). As shown in the example).

Also note I omitted the question mark (?), the question mark in this instance changes the character matching from greedy (match as much as possible) to lazy (match as few as possible).

Use it like so:

#users/([^/]+)/$#
白龙吟 2024-12-20 21:26:26

如果你想说“最后一个斜杠之后不应该有任何内容”,请说“字符串在最后一个斜杠之后结束”,即#users/(.+)/$#。省略问号也应该起作用,使加号“贪婪”,即尽可能多地匹配。

If you want to say "there should be nothing after the last slash", say "the string ends after the last slash", i.e. #users/(.+)/$#. Ommitting the question mark should also work, making the plus sign "greedy", i.e. matching as much as it can.

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