Javascript Regex仅允许2位数字和3位数字以逗号分隔

时间:2018-12-17 10:53:18

标签: javascript regex

我希望Java正则表达式可用于以下验证:

文本框应只允许2位数字和3位数字作为逗号分隔。 例如:12,123,56,567,789,11

5 个答案:

答案 0 :(得分:1)

嘿,欢迎来到Stackoverflow

尝试这个

  • ([0-9]{1,3},)*-最后两位或三位应为不带逗号

  • (\d{1,3},)*$-最后两位或三位数应该有逗号

  • (\d{2,3}),?-同时捕获大小写-最后两位是否有逗号

您可以在this website中在线测试正则表达式-确保选择了JavaScript

答案 1 :(得分:0)

欢迎!

尝试使用此正则表达式代替/([0-9]{2,3}),?/gi

这将捕获任何2或3位数字,而无需使用可选的,分隔符。

答案 2 :(得分:0)

也检查此正则表达式。

[0-9]{2,3}[,]{0,1}

https://regexr.com/452l2

答案 3 :(得分:0)

^               # 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

DEMO

答案 4 :(得分:0)

此正则表达式将匹配您的所有情况:^(?:\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);
相关问题