javascript正则表达式至少x个数字字符

时间:2014-02-12 16:39:48

标签: javascript regex

正则表达式,表示字符串中至少有10个数字字符。

可以超过10个,但不能少于。 在随机位置可以有任意数量的其他字符,将数字分开。

示例数据:

(123) 456-7890
123-456-7890 ext 41
1234567890
etc.

3 个答案:

答案 0 :(得分:2)

最简单的方法就是摆脱所有非数字字符并计算剩下的内容:

var valid = input.replace(/[^\d]/g, '').length >= 10

注意:.replace不会修改原始字符串。

答案 1 :(得分:2)

为了确保至少有10位数,请使用此正则表达式:

/^(\D*\d){10}/

<强>代码:

var valid = /^(\D*\d){10}/.test(str);

<强>测试

console.log(/^(\D*\d){10}/.test('123-456-7890 ext 41')); // true
console.log(/^(\D*\d){10}/.test('123-456-789')); // false

<强>解释

^ assert position at start of the string
1st Capturing group (\D*\d){10}
Quantifier: Exactly 10 times
Note: A repeated capturing group will only capture the last iteration.
Put a capturing group around the repeated group to capture all iterations or use a 
non-capturing group instead if you're not interested in the data
\D* match any character that's not a digit [^0-9]
Quantifier: Between zero and unlimited times, as many times as possible
\d match a digit [0-9]

答案 2 :(得分:1)

(\d\D*){10}

一个数字后跟任意数量的非数字,十次。