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 e.g.
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]*[-]*]
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 e.g.
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]*[-]*]
Share
Improve this question
asked Jul 9, 2016 at 21:55
CodeMonkeyCodeMonkey
2,2959 gold badges50 silver badges97 bronze badges
3
-
3
(?:\d[\s\-]*){6}
– Siguza Commented Jul 9, 2016 at 22:02 -
could you preprocess the string before you match? the issue is that the
{6,} says 6 matches, not 6 digits, so the last one has 6 matches (with the dash) and the top one matches because of
123-45` not because of the 6 digits. – mr rogers Commented Jul 9, 2016 at 22:02 - @Siguza that works !! Can you explain as well ? – CodeMonkey Commented Jul 9, 2016 at 22:03
3 Answers
Reset to default 4To 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