正则表达式来限制组中的特定字符 [英] Regex to limit specific characters within a group
问题描述
我努力改变当前的模式:
I struggle to change my current pattern:
^[\\\/0-9]{5,10}$
^[\\\/0-9]{5,10}$
检查输入内容是否由5-10个数字,斜杠或反斜杠组成. 我想将斜杠和反斜杠的总数最多限制为两个.
Which checks if input comprises of 5-10 numbers, slashes or backslashes. I would like to limit total slash and backslash count to two at most.
例如更改后 12345/\\9
无效:
e.g. 12345/\\9
should not be valid after the change:
我尝试将它们解剖成一个单独的组,例如 ^([\\\/]{0,2}[0-9]){5,10}$
,但是匹配错误.
I tried dissecting them into a separate group like so ^([\\\/]{0,2}[0-9]){5,10}$
but am getting wrong matches.
推荐答案
您可以使用锚定在测试两个全局条件"之一的字符串开头的超前模式来构建模式:字符串长度或斜杠数
You can build a pattern using a lookahead anchored at the start of the string that tests one of the two "global conditions": the string length or number of slashes.
要限制斜杠的数量,您可以这样设计图案:
To limit the number of slashes you can design your pattern like this:
^[0-9]*(?:[/\\][0-9]*){0,2}$
然后,您只需要在超前断言(?=...)
中添加字符串长度的条件即可:
Then you only have to add the condition for the string length in the lookahead assertion (?=...)
:
^(?=.{5,10}$)[0-9]*(?:[/\\][0-9]*){0,2}$
(请注意,只有当模式由斜杠分隔时,才必须转义正斜杠.否则,斜杠不是特殊字符.)
这篇关于正则表达式来限制组中的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!