![](/img/trans.png)
[英]How to allow only 2 digit numbers in html text input separated by colon?
[英]Javascript Regex to allow only 2 digit numbers and 3 digit numbers as comma separated
我想要正則表達式Javascript進行以下驗證:
文本框應僅允許2位數字和3位數字以逗號分隔。 例如:12,123,56,567,789,11
嘿,歡迎來到Stackoverflow,
試試這個
([0-9]{1,3},)*
-最后兩位或三位數應無逗號
(\\d{1,3},)*$
-最后兩位或三位應使用逗號
(\\d{2,3}),?
- 捕獲兩種情況 -后兩位是否有逗號
您可以在此網站上在線測試正則表達式-確保選擇了javascript
歡迎!
試試這個正則表達式,而不是/([0-9]{2,3}),?/gi
這將捕獲任何2個或3位數字,沒有可選的,
分離器。
^ # beginning of line
\d{2,3} # 2 or 3 digits
(?: # start non capture group
, # a comma
\d{2,3} # 2 or 3 digits
)* # end group may appear 0 or more times
$ # end of line
如果您不想以0
開頭的數字,例如025
^ # beginning of line
[1-9] # digit fomr 1 to 9
\d # 1 digit
\d? # 1 optional digit
(?: # start non capture group
, # a comma
[1-9] # digit fomr 1 to 9
\d # 1 digit
\d? # 1 optional digit
)* # end group may appear 0 or more times
$ # end of line
此正則表達式將匹配您的所有情況: ^(?:\\d{2,3},)+(\\d{2,3}),?$|^\\d{2,3}$
https://regex101.com/r/CdYVi9/2
樣本JS:
const isValid = str => /^(?:\d{2,3},)+(\d{2,3}),?$|^\d{2,3}$/.test(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.