[英]Regular expression for allow - not more then 2 times
i am using ^(^[az]?[a0-z9]+[.|-][a0-z9]+[az]+[.|-][a0-z9]+[az]?$)+$
, this force user type 2 hyphen(-) in his expression .... 我正在使用^(^[az]?[a0-z9]+[.|-][a0-z9]+[az]+[.|-][a0-z9]+[az]?$)+$
,这会迫使用户在其表达式中键入2个连字符(-)。
But i need that regular expression can allow maximum 2 hypen and minimum one hyphen in his expression.... 但是我需要正则表达式可以在他的表达式中允许最多2个连字符和最小一个连字符....
This is a simple re implementation. 这是一个简单的重新实现。
/^[^-]+(-[^-]+){1,2}$/
And the test result: 以及测试结果:
"123".match(/^[^-]+(-[^-]+){1,2}$/)
null
"123-123".match(/^[^-]+(-[^-]+){1,2}$/)
["123-123", "-123"]
"123-123-123".match(/^[^-]+(-[^-]+){1,2}$/)
["123-123-123", "-123"]
"123-123-123-123".match(/^[^-]+(-[^-]+){1,2}$/)
null
And if you just copy one from other, then you should try to write one by yourself. 而且,如果您只是复制一个,那么您应该尝试自己编写一个。
If not, you should delete it and restart. 如果不是,则应将其删除并重新启动。
^[^-]*-+[^-]*-{0,1}[^-]*$
String1: abc-pqr, String2: aaa-bbb, String3 aaa-bbb-ccc-ddd, where String 1 and 2 are valid and 3 is invalid? 字符串1:abc-pqr,字符串2:aaa-bbb,字符串3 aaa-bbb-ccc-ddd,其中字符串1和2有效,而3无效?
This allows String 1 and 2. But not 3. 这允许字符串1和2,但不允许3。
This regex should work... 这个正则表达式应该工作...
/^[^-]*-[^-]*-[^-]*$/
It works by capturing anything except a hyphen (zero or more times), then a hyphen, then anything else again, then another hyphen, then anything else. 它的工作原理是捕获除连字符(零次或多次)之外的所有内容,然后捕获连字符,再捕获其他任何东西,再捕获另一个连字符,再捕获其他任何东西。 It has a start and end marker to ensure that the whole string does not contain any more hyphens. 它具有一个开始和结束标记,以确保整个字符串不再包含连字符。
Breaks down like this... 像这样分解...
/ # begin regex
^ # start of string
[^-]* # not hyphen ([^-]), zero or more times (*)
- # hyphen
[^-]* # not hyphen ([^-]), zero or more times (*)
- # hyphen
[^-]* # not hyphen ([^-]), zero or more times (*)
$ # end of string
/ # end regex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.