简体   繁体   English

javascript中只能访问小数和数字的正则表达式

[英]Regular expression in javascript that access decimals and numbers only

I want to make regular expression which supports all below numbers,我想制作支持以下所有数字的正则表达式,

  • Max length of the number : 7号码的最大长度:7
  • Max length of decimal places: 2小数位最大长度:2

Example:例子:

  • Valid : 500, 1234567, 350.75, 7500.05, 4500.3有效: 500, 1234567, 350.75, 7500.05, 4500.3
  • Not valid : 100.123, 12345678, 45000.25无效:100.123、12345678、45000.25

I tried with我试过

<input type='number' pattern="/^\\d{1,7}(\\.\\d{1,2})?$/"/>

but its not satisfying the max length value.但它不满足最大长度值。

Kindly help in this issue.请帮助解决这个问题。

Check length via lookahead.通过前瞻检查长度。

               ↓               ↓       CHANGE THESE PARAMETERS
/^(?=(.[.]?){1,7}$)\d*([.]\d{1,2})?$/
  |---------------|                    LOOK-AHEAD TO CHECK LENGTH
                   |-|                 INTEGER PORTION OF NUMBER
                      |-----------|    OPTIONAL DECIMAL PORTION OF NUMBER

This is more easily scalable to variations of the problem such as "up to seven total digits with up to four decimal places" than other solutions are.与其他解决方案相比,这更容易扩展到问题的变体,例如“最多七位总位数,最多四位小数”。 Just replace the two characters pointed to by "CHANGE THESE PARAMETERS".只需替换“更改这些参数”所指向的两个字符即可。

Pretty sure this will do it for ya:很确定这会为你做到:

^(\d{1,5}\.\d{2}|\d{1,6}\.\d|\d{1,7})$

Anything that is 5.2 or 6.1 or 7 digits (max number of characters)任何 5.2 或 6.1 或 7 位数字(最大字符数)

Here's a jsbin for the pattern.这是模式的jsbin

var re = /^(\d{1,7}|\d{1,6}\.\d|\d{1,5}\.\d{1,2})$/;

function validate(str) {
  return (str).match(re) !== null;
}

function assert(value, expected) {
  return value === expected;
}

console.log(
  assert(validate("1234567"), true)
);

console.log(
  assert(validate("123456.7"), true)
);

console.log(
  assert(validate("12345.67"), true)
);

console.log(
  assert(validate("1234.567"), false)
);

console.log(
  assert(validate("12345.678"), false)
);

console.log(
  assert(validate("123456.78"), false)
);

console.log(
  assert(validate("1234567.8"), false)
);

console.log(
  assert(validate("12345678"), false)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM