[英]How to write this regexp?
I am validating a field which may NOT be anything but numbers, but may include a space or a minus-sign. 我正在验证的字段可能不是数字,而是数字,但可能包含空格或减号。
This is for validating phone number field! 这是用于验证电话号码字段! So, these criterias should be met: (might have forgot a criteria, if so remind me)
因此,应该满足以下条件:(可能忘记了条件,请提醒我)
1- Atleast 5 numbers
2- May contain space
3- Not shorter than 5 characters
4- Not longer than 20 characters
5- May contain minus-sign
6- Not empty
if (nr.length>4 && nr.length<21 && nr!=''){
}
How should I write the regexp? 我应该如何编写正则表达式? Or the if statement?
还是if语句?
Thanks 谢谢
Try this regular expression: 试试这个正则表达式:
^(?=(?:\D*\d){5})[\d -]{5,20}$
The lookahead assertion (?=(?:\\D*\\d){5})
tests for the five digits. 前瞻断言
(?=(?:\\D*\\d){5})
测试五个数字。 The rest tests the length of at least 5 and at most 20 characters that can only be digits, the space or hyphen character. 其余测试的长度至少为5个字符,最多为20个字符,只能是数字,空格或连字符。
The nr != ''
condition is redundant since the length comparisons already exclude a length of zero. nr != ''
条件是多余的,因为长度比较已经排除了零长度。
So with the length comparisons out of the way, it looks like you're down to a simple character class of digits, spaces, and dashes: 因此,在不进行长度比较的情况下,您似乎只能使用数字,空格和破折号的简单字符类了:
/[\d\s-]{5,20}/
Of course, this allows things like ----- or a bunch of spaces. 当然,这允许类似-----或一堆空格的事情。 So maybe you want to remove everything that's not a digit first, then just check for
因此,也许您想先删除所有不是数字的内容,然后再检查
/\d{5,20}/
which would probably be simpler. 这可能会更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.