簡體   English   中英

javascript正則表達式,至少x個數字字符

[英]javascript regex for at least x numeric characters

一個正則表達式,表明一個字符串中至少有10個數字字符。

可以超過10,但不能少於10。 隨機位置可以有任意數量的其他字符,以數字分隔。

示例數據:

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

去除所有非數字字符並計算剩余的數量可能是最簡單的:

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

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

為了確保至少有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]
(\d\D*){10}

一個數字后跟任意數量的非數字十次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM