I'm trying to create a regular expression using javascript for react application that allow negative and positive decimal numbers and not allow enter any character.
I've been looking for examples, reading documentation but I dont know how make it.
This are the things that have to do:
allow negative and positive decimal numbers, I found this:
var re = new RegExp("^[+-]?[0-9]{0,900}(?:\.[0-9]{0,900})?$");
but I can write a character and show me true and add other character and show me false. console.log(re.test(value));
if is decimal and starts with zero show zero (0.232) and dont allow this (.232)
dont allow write characters, I've seen this /^\\d*$/
Looking at the documentation about RegExp it states that when using the constructor function, the normal string escape rules (preceding special characters with \\ when included in a string) are necessary.
Your regex would then match a dot which would match any character making for example a
valid because the preceding [0-9]{0,900}
matches zero - 900 times.
Your regex would become:
var re = new RegExp("^[+-]?[0-9]{0,900}(?:\\.[0-9]{0,900})?$");
To match negative and positive decimal numbers that should not start with a dot, you could use:
Which will match the beginning of the string ^
, an optional [+-]?
, one or more digits [0-9]+
followed by an optional part which will match a dot and one or more digits (?:\\.[0-9]+)?
and then the end of the string $
.
var re = new RegExp("^-?[0-9]+(?:\\.[0-9]+)?$");
var re = new RegExp("^[+-]?[0-9]+(?:\\\\.[0-9]+)?$"); var strings = [ "1", "1.2", "0.232", ".232", "-1.2", "+1.2" ]; strings.forEach((s) => { console.log(s + " ==> " + re.test(s)); });
I use this:
^-?[0-9]\d*(\.\d+)?$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.