[英]How to limit number of digits in regex
我正在使用 match 僅返回輸入中的數字。 我需要將輸入的位數限制為 2。我該怎么做?
const numbers = input.match(/[0-9]+/g);
我們可以匹配正則表達式模式^[0-9]{1,2}
:
var input = "12345"; const numbers = input.match(/^[0-9]{1,2}/); console.log(input + " => " + numbers);
請注意,我們使用^[0-9]{1,2}
而不是^[0-9]{2}
因為用戶可能只輸入一個數字。
const input = "1234567890"; const regex = /^\d{2}$/; const isTwoDigits = regex.test(input); if (isTwoDigits) { console.log("The input contains exactly 2 digits"); } else { console.log("The input does not contain exactly 2 digits"); }
也許您可以使用屬性maxlength="2"
作為輸入
讓它寫成兩個數字的最簡單方法是兩個數字
const numbers = input.match(/[0-9][0-9]/g);
另一種方法是將其寫為計數為 2 的數字
const numbers = input.match(/[0-9]{2}/g);
也許你需要允許輸入 1 個數字
const numbers = input.match(/[0-9][0-9]?/g);
const numbers = input.match(/[0-9]|[0-9][0-9]/g);
const numbers = input.match(/[0-9]{1,2}/g);
這將是您的正則表達式:
const numbers = input.match(/[0-9]{1,2}/);
我還將解釋一些其他答案可能不清楚的事情。
如果你用^
開始你的正則表達式,只有當字符串以它們開頭時你才會得到前 2 個數字:
const numbers = input.match(/^[0-9]{1,2}/);
如果你 append g
到你的正則表達式,你會得到所有的數字對,而不僅僅是第一個
const numbers = input.match(/[0-9]{1,2}/g);
為了更簡單地編寫正則表達式,我建議使用https://regex101.com ,因為它有一個實時測試器和帶有示例的完整備忘單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.