Regex至少匹配n次,但不超过m次

时间:2022-08-03 08:54:18

I want a regular expression that could match the string %*--- with at least 1 hyphen but the expression should not be matched if there are more than 3 hyphens.![enter image description here][1] So far I have come up with /^%?\*{1}\s*(\- *){1,3}/ but it is still matching when the hyphens exceed 3.

我想要一个正则表达式,它可以匹配字符串%*--- ---至少有一个连字符,但是如果连字符超过3个,则表达式不应该匹配。[在这里输入图像描述][1],到目前为止我已经想出/ ^ % ?\*{1}\s*(\- *){1,3}/但当连字符超过3时,仍在匹配。

I have also tried ? after the range {1,3} but its not meeting the requirement.

我也试过了?范围{1,3}但不满足要求。

3 个解决方案

#1


3  

Although it's often written as {min,max} in tutorials and references, the enumerated quantifier does not mean not more than max. If it sees three hyphens, -{1,3} will consume all three, but it doesn't care what the next character is (if there is one). It's just like all other quantifiers in this regard: it consumes as much as it can, then it hands control to the next part of the regex.

尽管在教程和引用中经常被写入{min,max},但是枚举量词并不意味着不超过max。如果它看到三个连字符,-{1,3}将消耗所有3个字符,但它并不关心下一个字符是什么(如果有)。它与这方面的所有其他量词一样:它尽可能地消耗,然后将控制权交给regex的下一部分。

That's why the other responders suggested using an end anchor ($). If you can't use an anchor, or don't want to, you can use a negative lookahead instead:

这就是为什么其他应答器建议使用end锚($)。如果你不能使用锚,或者不想使用锚,你可以使用消极的前视:

/^%\*-{1,3}(?!-)/

#2


0  

^(?!(.*?-){4})(?=.*?-).*$

You can try this.The lookahead will make sure there are no more than 3 - and at least 1.See demo.

你可以试试这个。前视将确保不超过3 -和至少1。看到演示。

https://regex101.com/r/fX3oF6/12

https://regex101.com/r/fX3oF6/12

#3


0  

You need a $ at the end, and your regex can be greatly simplified:

最后你需要一美元,你的正则表达式可以大大简化:

/^%\*--?-?$/

See demo.

看到演示。

#1


3  

Although it's often written as {min,max} in tutorials and references, the enumerated quantifier does not mean not more than max. If it sees three hyphens, -{1,3} will consume all three, but it doesn't care what the next character is (if there is one). It's just like all other quantifiers in this regard: it consumes as much as it can, then it hands control to the next part of the regex.

尽管在教程和引用中经常被写入{min,max},但是枚举量词并不意味着不超过max。如果它看到三个连字符,-{1,3}将消耗所有3个字符,但它并不关心下一个字符是什么(如果有)。它与这方面的所有其他量词一样:它尽可能地消耗,然后将控制权交给regex的下一部分。

That's why the other responders suggested using an end anchor ($). If you can't use an anchor, or don't want to, you can use a negative lookahead instead:

这就是为什么其他应答器建议使用end锚($)。如果你不能使用锚,或者不想使用锚,你可以使用消极的前视:

/^%\*-{1,3}(?!-)/

#2


0  

^(?!(.*?-){4})(?=.*?-).*$

You can try this.The lookahead will make sure there are no more than 3 - and at least 1.See demo.

你可以试试这个。前视将确保不超过3 -和至少1。看到演示。

https://regex101.com/r/fX3oF6/12

https://regex101.com/r/fX3oF6/12

#3


0  

You need a $ at the end, and your regex can be greatly simplified:

最后你需要一美元,你的正则表达式可以大大简化:

/^%\*--?-?$/

See demo.

看到演示。