正则符合条件不超过一个尾声

发布于 2025-02-01 13:07:55 字数 263 浏览 2 评论 0原文

寻找不超过1次匹配的正则是我尝试过的尾声

api/v1
/api/v1
/api/2v1/21/
/api/blah/v1/
/api/ether/v1//
/api/23v1///

预期的匹配

/api/v1
/api/2v1/21/
/api/blah/v1/

^\/([^?&#\s]*)(^[\/{2,}\s])$

Looking for a regex to not match more than 1 occurrence of a trailing slash

api/v1
/api/v1
/api/2v1/21/
/api/blah/v1/
/api/ether/v1//
/api/23v1///

Expected match

/api/v1
/api/2v1/21/
/api/blah/v1/

What I tried:

^\/([^?&#\s]*)(^[\/{2,}\s])$

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

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

发布评论

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

评论(3

注定孤独终老 2025-02-08 13:07:55

通过使用负 lookahead

^(?!.*//)/.*

请参阅Regex101的此演示

By use of a negative lookahead:

^(?!.*//)/.*

See this demo at regex101

旧故 2025-02-08 13:07:55

在您尝试的模式中,模式的第二部分无法匹配,它断言字符串的开始代码>(^[\/{2,} \ s])$ 直接断言字符串的结尾。

^\/([^?&#\s]*)(^[\/{2,}\s])$

              ^^^^^^^^^^^^^^

但是您已经断言字符串的开始:^\/

您可以重复一个以/开始的模式,然后重复1倍以上的字符类:

^(?:\/[^\/?&#\s]+)+\/?$

说明

  • ^字符串开始
  • (?:\/[^\/?#&&&&&&&s]+)+)+重复1倍以上< 1+ char以外的列表
  • \/?
  • 可选

代码>/和 href =“ https://regex101.com/r/wvnxpx/1”

In the pattern that you tried, the second part of the pattern can not match, it asserts the start of the string ^ and then matches a single character in the character class (^[\/{2,}\s])$ directly followed by asserting the end of the string.

^\/([^?&#\s]*)(^[\/{2,}\s])$

              ^^^^^^^^^^^^^^

But you have already asserted the start of the string here ^\/

You can repeat a pattern starting with / followed by repeating 1+ times the character class that you already have:

^(?:\/[^\/?&#\s]+)+\/?$

Explanation

  • ^ Start of string
  • (?:\/[^\/?&#\s]+)+ Repeat 1+ times / and 1+ char other than the listed ones
  • \/? Optional /
  • $ End of string

See a regex demo

宁愿没拥抱 2025-02-08 13:07:55

您可以使用

^(?:/[^/?&#\s]+)*/?$

regex demo

详细信息

  • 的开始
  • ^ -字符串 / char后面有一个或多个字符,除/&amp;##和whitespace
  • /? - 可选的/
  • $ $ - 字符串的结尾。

You can use

^(?:/[^/?&#\s]+)*/?$

See the regex demo.

Details

  • ^ - start of string
  • (?:/[^/?&#\s]+)* - zero or more repetitions of a / char followed with one or more chars other than /, ?, &, # and whitespace
  • /? - an optional /
  • $ - end of string.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文