[英]how to limit the number of “/” in a string
How do I use lookahead assertion to limit by range the number of "/" 如何使用超前断言来限制范围“/”的数量
I have tired the following 我厌倦了以下
^(?=/{1,3})$
^(?= / {1,3})$
but it doesn't work 但它不起作用
The easiest solution is to use a negative lookahead: 最简单的解决方案是使用负向前瞻:
^(?!(?:[^/]*/){4})
That basically means the string cannot contain 4 slashes. 这基本上意味着字符串不能包含4个斜杠。
This assumes you allow other characters between slashes, but a maximum of 3 slashes. 假设您允许斜杠之间的其他字符,但最多允许3个斜杠。
A positive version would be ^(?=[^/]*(?:/[^/]*){0,3}$)
or ^[^/]*(?:/[^/]*){0,3}$
, without the lookahead. 正面版本将是
^(?=[^/]*(?:/[^/]*){0,3}$)
或^[^/]*(?:/[^/]*){0,3}$
,没有前瞻。 Of course, the problem is trivial without regular expressions, if possible. 当然,如果可能的话,如果没有正则表达式,问题就是微不足道的。
Lets try to break that last one down: 让我们尝试打破最后一个:
^
- Start of the string. ^
- 字符串的开头。 [^/]*
- Some characters that are not slashes (or none) [^/]*
- 一些不是斜杠的字符(或者没有) (?: )
- A logical group. (?: )
:) - 一个逻辑组。 Similar to ()
, but does not capture the result (we do not need it after validation) ()
类似,但不捕获结果(验证后我们不需要它) /[^/]*
- Slash, followed by non-slash characters. /[^/]*
- 斜杠,后跟非斜杠字符。 {0,3}
- From 0 to 3 times. {0,3}
- 从0到3次。 $
- End of the string. $
- 字符串结束。 您可以尝试以下(您必须说应该没有/之后):
^(?=/{1,3}([^/]|$))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.