[英]Javascript Regular expression for basic digits with decimal points?
我试图使用正则表达式来验证十进制值。 我写下面的正则表达式,但它不允许第一个小数点值为.5或.6或.1
常规Exp :/ /^\\d[0-9]{0,13}(\\.\\d{1,2})?$/
规则:
示例 - 有效输入
示例 - 输入无效
const valid = [ "0", "0.5", "1.55", ".5", "1234567890123", "1234567890123.5", "1234567890123.00", ]; const invalid = [ ".", ".0", "1.234", "5.", "12345678901234", "12345678901234.56", ]; const rgx = /^\\d[0-9]{0,13}(\\.\\d{1,2})?$/ console.log("Checking valid strings (should all be true):"); valid.forEach(str => console.log(rgx.test(str), str)); console.log("\\nChecking invalid strings (should all be false):"); invalid.forEach(str => console.log(rgx.test(str), str));
我相信以下正则表达式应符合您的所有标准:
^(\d{1,13}($|\.\d?\d$)|\.[1-9]\d?$)
第一种情况:1-13位数字后跟任何一个或“。” 后跟一两位数字
第二种情况:“。” 接着是非零数字,最多是另一个数字
const valid = [ "0", "0.5", "1.55", ".5", "1234567890123", "1234567890123.5", "1234567890123.00", ]; const invalid = [ ".", ".0", "1.234", "5.", "12345678901234", "12345678901234.56", ]; const rgx = /^(\\d{1,13}($|\\.\\d?\\d$)|\\.[1-9]\\d?$)/ console.log("Checking valid strings (should all be true):"); valid.forEach(str => console.log(rgx.test(str), str)); console.log("\\nChecking invalid strings (should all be false):"); invalid.forEach(str => console.log(rgx.test(str), str));
我认为这应该完成你的大部分要求,但不是全部,限制为小数点后9位
( /^(\d+\.?\d{0,9}|\.\d{1,9})$/ )
而这一个没有小数限制
( /^(\d+\.?\d*|\.\d+)$/ )
其他答案不允许.0x的情况,我认为是有效的? 我认为你需要分别测试xxx [.xx]和.xx
^(\d{1,13}(\.\d{1,2})?|\.(0[1-9]|[1-9]\d?))$
要匹配你的价值观,你可以使用非捕获组与交替使用|
并指定您要匹配的内容。
^(?:\\.[1-9][0-9]?|\\d{1,13}(?:\\.\\d{1,2})?|.\\d{2})$
这也将匹配.01
而不是.0
说明
^
字符串的开头 (?:
非捕获组
\\.[1-9][0-9]?
匹配点后跟0,然后是0-9 |
要么 \\d{1,13}
匹配1 - 13位数 (?:
非捕获组
\\.\\d{1,2}
匹配一个点和1或2位数 )?
关闭非捕获组并使其可选 |
要么 .\\d{2}
匹配点后跟2位数 )
关闭非捕获组 $
结束字符串 const valid = [ "0", ".01", "0.5", "1.55", ".5", "1234567890123", "1234567890123.5", "1234567890123.00", ]; const invalid = [ ".", ".0", "1.234", "5.", "12345678901234", "12345678901234.56", ]; const rgx = /^(?:\\.[1-9][0-9]?|\\d{1,13}(?:\\.\\d{1,2})?|.\\d{2})$/; console.log("Checking valid strings (should all be true):"); valid.forEach(str => console.log(rgx.test(str), str)); console.log("\\nChecking invalid strings (should all be false):"); invalid.forEach(str => console.log(rgx.test(str), str));
为了不匹配.01
你可以使用:
^(?:\\d{1,13}(?:\\.\\d{1,2})?|\\.[1-9][0-9]?)$
const valid = [ "0", "0.5", "1.55", ".5", "1234567890123", "1234567890123.5", "1234567890123.00", ]; const invalid = [ ".", ".0", ".01", "1.234", "5.", "12345678901234", "12345678901234.56", ]; const rgx = /^(?:\\d{1,13}(?:\\.\\d{1,2})?|\\.[1-9][0-9]?)$/; console.log("Checking valid strings (should all be true):"); valid.forEach(str => console.log(rgx.test(str), str)); console.log("\\nChecking invalid strings (should all be false):"); invalid.forEach(str => console.log(rgx.test(str), str));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.