I am writing a regex to match number of digits. The whole string can have atleast 6 digits and can have spaces and dashes.
for eg
123-45 6 valid
123456 valid
123-56 Invalid
Initially i wrote a regex that took care of minimum of 6 chars in the string. However, it did not work as it was counting the dashes and spaces as part of 6.
[\d\s-]{6,}
Tried
[\d]{6,}[\s-]
even this one is not working. Can you suggest how to fix this.
Another Attempt:
[[\d]{6,}[\s]*[-]*]
To check for the presence of at least 6 digits you can use /(?:\\d\\D*){6,}/
. If you also want it to only allow space and dash, you could adjust the pattern to /^[ -]*(?:\\d[ -]*){6,}$/
The solution using String.replace
and String.match
functions:
var isValid = function(str){
var match = str.replace(/[\s-]/g, "").match(/^\d{6,}$/);
return Boolean(match);
};
console.log(isValid("123-45 6")); // true
console.log(isValid("12345678")); // true
console.log(isValid("123-56")); // false
console.log(isValid("123-567<")); // false
You can do it either like this (accepts spaces and dashes at the end):
(\d[\s-]*){6,}
or like this (only dashes and spaces between digits):
(\d[\s-]*){5,}\d
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.