Click here to Skip to main content
16,022,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am looking for a regex expression that will allow entry from -1.*** to 1.***.
i.e. from negative of 1 that allows upto 3 digit after decimal (that can be any digit from 1 to 9) TO positive of 1 (that allows upto 3 digit after decimal that can be any digit from 1 to 9).

Example of entry that should be allowed:
-1.999, -1.987, -1.234, 0.123, 0.567, 0.987. 0.999, 1.543. 1.999

Example of entry that should not be allowed:
-2.000, -2.987, -9.987, -2.001

How can this be done?

What I have tried:

Tried on few links: https://regex101.com/r/5TxLfU/1[^]

Not able to get the correct answer.
Posted

1 solution

This should be as simple as something like this:
regexp
^-?(0(\.\d{1,3})?|1(\.\d{1,3})?)$
 
Share this answer
 
v2
Comments
Codes DeCodes 1-Oct-24 8:47am    
This expression works perfectly when I test on https://www.trackingplan.com/regex-tester but fails when I use in my typescript code.

Sample code that I am using:
private regex: RegExp = new RegExp(/^-?(0(\.\d{1,3})|1(\.\d{1,3}))$/g);

var result = this.regex.test(input); //input is user input which I am checking by event onKeyDown.

I am trying to enter 1.001, so on press on 1, "this.regex.test(1);" will return value as false.
Pete O'Hanlon 1-Oct-24 9:42am    
If you are running the check after every keypress, you are going to get invalid values. In reality, you shouldn't perform the check after the keypress because, even if you add in 1 and 0 as valid values to your test, what about 1. or 0.? If you tab out of the data entry, leaving these values in, they are going to be invalid even if you added them as possible combinations. What you would be better off doing is either to debounce the field to allow a certain amount of time before running the test, or you just report that it's true or false.

To allow 1 or 0 as possible values as well, just change the regular expression to this one:
^-?(0(\.\d{1,3})?|1(\.\d{1,3})?)$

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900