我需要帮助的正则表达式,接受任何7位到10位数字(无小数),连同连字符或空格之间的任何地方在数字。
例如,
下面是有效的方案
0123456789
000-25-392-93
0-1-2-3-4-5-6-7-8-9
0 1-2 3-4 5-6 7有些人能提供最好的准则来接受这一点吗?
发布于 2021-04-27 09:17:03
^(?:\d[- ]?){7,10}$也可以工作。
\d表示数字。[- ]?,用于检查在最后一个数字之后是否有一个space or -{7,10}检查它是否在7到10之间发布于 2021-04-27 09:08:55
试试这个正则表达式:
^\d(?:[- ]*\d){6,9}$^\d从一个数字开始。(?:[- ]*\d){6,9}后面跟着另一个数字,中间有任意数量的-或空格,重复6到9次,所以总共重复7到10位数。$字符串的结尾。见测试用例
const texts = [
'0123456789',
'000-25-392-93',
'0-1-2-3-4-5-6-7-8-9',
'0 1-2 3-4 5-6 7'
];
const regex = /^\d(?:[- ]*\d){6,9}$/;
console.log(texts.map(text => regex.test(text)));
发布于 2021-04-27 09:17:17
这里有一种方法可以做到。
const numbers = [
"0123456789",
"000-25-392-93",
"0-1-2-3-4-5-6-7-8-9",
"0 1-2 3-4 5-6 7",
"01234" , // not valid
"33300409383850", // not valid
"123abc456def78" // not valid
];
const valid = numbers.filter(num => {
// count numerical digits by stripping out any non numerical characters
//const len = num.replace(/\D/g, "").length; // removes non numerical digits
const len = num.replace(/[\s\-]/g, "").length; // removes dashes and spaces
// now we will only accept elements where their digit count is between 7 and 10
return len > 6 && len < 11;
});
console.log(valid);
https://stackoverflow.com/questions/67279024
复制相似问题