I need a regex to limit number digits to 10 even if there are spaces.
For example it allows 06 15 20 47 23
the same as 0615204723
.
I tried: ^\d{10}$
, but how do I ignore spaces?
Also, the number should start with 06
or 07
. (Editor's note, the last requirement was from comments by the OP.)
This will do it in most regex systems. (You need to state what language you are using!)
/^\s*(0\s*[67]\s*(?:\d\s*){8})$/
But assuming you really only want the number, then go ahead and break it into 2 steps.
For example, in JavaScript:
var s = ' 06 15 20 47 34 ';
s = s.replace (/\s/g, "");
isValid = /^0[67]\d{8}$/.test (s);
I had the same problem, I noticed if I grouped each digit with any number of spaces padding the front and back, I got the solution I was looking for. In this example, ignores all spaces
^(\s*\d\s*){10}$
eg. "1234567890"
" 12 34 567 89 0 "
In a more complicated example, this ignored all spaces, dashes, round braces and spaces.
^([\s\(\)\-]*\d[\s\(\)\-]*){10}$
eg. "(123)456-7890"
" ( 12 (3)( - 45 - 6-78 )(90 (((-- "
Test them out here, it will provide you with the code for your given system:
http://www.myregextester.com/index.php
Slightly preferable:
"^\s?(\d\s?){10}$"
Where \s is any whitespace and \d is a digit. This allows for leading as well as infixed and trailing spaces.
(\s*\d\s*){0,10}
This should allow leading and trailing spaces around digits, and match 0 to 10 digits.
var str = " a b c d e f g ";
var newStr = str.replace(/\s+/g, '');