Regular expression to require 10 digits without considering spaces

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 10:12:34

问题


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.)


回答1:


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);



回答2:


You can do:

"^(\d *){10}$"




回答3:


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




回答4:


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.




回答5:


(\s*\d\s*){0,10}

This should allow leading and trailing spaces around digits, and match 0 to 10 digits.




回答6:


var str = " a b c d e f g "; 
var newStr = str.replace(/\s+/g, ''); 


来源:https://stackoverflow.com/questions/7126345/regular-expression-to-require-10-digits-without-considering-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!