سؤال

I've found a similar question on SO, but nothing I can get my head around. Here's what I need;

6 or more digits, with these characters allowed \s\-\(\)\+

So here's what I have /^[0-9\s\-\(\)\+]{6,}$/

The problem is, I don't want anything other than the number to count towards the 6 or more quantifier. How can I only "count" the digits? It would also been good if I could stop those other allowed characters from being entered adjacently e.g:

0898--234 
+43 34  434

After an hour of reading up and looking at a regex cheat sheet, I'm hoping some kind person can point me in the right direction!

هل كانت مفيدة؟

المحلول

You could do something like this:

/^([\s()+-]*[0-9]){6,}[\s()+-]*$/

This will match any number of special characters (whitespace, parentheses, pluses or hyphens) followed by a single decimal digit, repeated 6 or more times, followed by any number of special characters.

Or this if you don't want to match two or more adjacent special characters:

/^([\s()+-]?[0-9]){6,}[\s()+-]?$/

نصائح أخرى

You can use lookahead:

/^(?=(\D*\d){6,})[0-9\s()+-]{6,}$/
/^[\s()+-]*(\d[\s()+-]*){6,}$/

This doesn't count the 'cruft'. It allows any number of special characters, followed by six times [a digit followed by any number of special characters].
If you want max. one special character in between digits, use ? instead of *, but I assume you don't care much for more than one special character at the start or at the end, so I'd go with

/^[\s()+-]*(\d[\s()+-]?){6,}[\s()+-]*$/

This matches any number of special characters, followed by 6 or more times [a digit followed by at most one special character], followed by any number of special characters.


Another option would be to strip your special characters from the string first, and then match against 6 or more digits.

var rawInput = "    12  (3) -- 4 -5 ++6";
var strippedInput = rawInput.replace(/[\s()+-]*/g, "");
return new RegExp("^\d{6,}$").test(strippedInput);

Remember that you have a complete programming language at your disposal. I've noticed people tend to decide they need to use regex and then forget about everything else they can do.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top