How to write regular expressions?
problem description
validate the entered data. You can only enter data between 0 and 1. 0 cannot be entered, 1 can be entered, and there are only 2 decimal places. How to write a regular expression with only 2 decimal places?
0.0 and 0.00 also fail validation, while 1.0 and 1.00 can pass verification
after writing, it is recommended to test the following data:
0 0.0 0.00 1 1.0 1.00 0.3 0.34
the environmental background of the problems and what methods you have tried
related codes
/ / Please paste the code text below (do not replace the code with pictures)
/^(0\.[0-9]{1,2}|1)$/
what result do you expect? What is the error message actually seen?
/ ^ (0. ([1-9] {1} [0-9] {0 answer 1} | [0-9] {1} [1-9] {1}) | 1) $/
regular I am not familiar with either. can read this article
< hr class=" answer >.
since it is validating data, this rule can of course be written out, but it is actually very inefficient to write it out if you want to take into account both the matching format and boundary conditions of the data.
your requirement can actually be divided into three small parts:
- first of all, we should rule out the meaningless numbers of 0, 0, 0, 0, and 0. 00.
- to satisfy the format of 0.xx decimal
- to be able to enter 1
for the second article, you can write it with rules, such as ^ 0\. [1-9] + $
. Then for the other two conditions, you can get the verification results in advance by comparing parseFloat with 1
and 0
respectively. In fact, there is no need to write these two into the rules.
/^(0\.[1-9][0-9]?|0\.0[1-9]|1)$/
I don't know if it can be satisfied, but xxx.test (Num), Num is best in the form of a string.
my personal test is effective.
var regx = /^(0(?!\.00)|1(?=\.00))\.[0-9]{1,2}$/
regx.test('0.00')//false
regx.test('1.00')//true
regx.test('0.11')//true
upgrade version, , try again. I tried ok. I didn't see the question clearly just now
/(^((0(?!\.00|\.0)|1(?=\.00))\.[0-9]{0,2})$)|(^1$)|(^0\.0[1-9]{1}$)|(^1\.0$)/