正则符合条件不超过一个尾声
寻找不超过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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过使用负 lookahead :
请参阅Regex101的此演示
By use of a negative lookahead:
See this demo at regex101
在您尝试的模式中,模式的第二部分无法匹配,它断言字符串的开始代码>(^[\/{2,} \ s])$ 直接断言字符串的结尾。
但是您已经断言字符串的开始:
^\/
您可以重复一个以
/
开始的模式,然后重复1倍以上的字符类:说明
^
字符串开始(?:\/[^\/?#&&&&&&&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.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:Explanation
^
Start of string(?:\/[^\/?&#\s]+)+
Repeat 1+ times/
and 1+ char other than the listed ones\/?
Optional/
$
End of stringSee a regex demo
您可以使用
regex demo 。
详细信息
^
-字符串/
char后面有一个或多个字符,除/
,?
,&amp;
,,
##
和whitespace/?
- 可选的/
$
$ - 字符串的结尾。You can use
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.