I have this REGEX almost perfect ... It seems to handle everything except a number that leads with a negative sign and then a decimal. So if I enter:
-.2
I get an error -
Here is my Regex -- everything else I've tested works perfectly...
^(\+|-)?[0-9]{1,11}?(?:\.[0-9]{1,4})?$
This allows for:
These all work:
-0.2345
-10
12
.125
0.1245
5.555
25000000000 (aka 25 Billion)
25000000000.25
These do not work:
-.2
-.421
To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.
To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets. For example, [A-CX-Z] matches 'A' or 'B' or 'C' or 'X' or 'Y' or 'Z'.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99.
What is RegEx Validation (Regular Expression)? RegEx validation is essentially a syntax check which makes it possible to see whether an email address is spelled correctly, has no spaces, commas, and all the @s, dots and domain extensions are in the right place.
Regex can be expensive... Why not use Decimal.Parse or Float.parse?
Your current implementation would never work with alternate number styles, like European where . (dot) and , (comma) are interchanged ...whereas Decimal.Parse will:
string stringValue = "45.889,33";
CultureInfo currentCulture = Thread.CurrentCulture; //set this way up in the execution chain
decimal thenumber = Decimal.Parse(stringValue, currentCulture);
//thenumber = 45889.33 in us-en display format.
Numerical parsing is not a good application for regex, IMO.
Try this:
^(\+|-)?[0-9]{0,11}?(?:\.[0-9]{1,4})?$
Update:
The above regex accepts strings +
, -
and (the empty string). You can use a lookahead to restrict those. The lookahead ensures there must be a character after the
+
or -
sign.
The correct solution is:
^(\+|-)?(?=.{1})[0-9]{0,11}(?:\.[0-9]{1,4})?$
A working example:
Strings accepted:
-0.2345
-10
12
.125
0.1245
5.555
-.2
-.421
Strings not accepted:
100000000000.0001
+
-
123456789012
1111111111.12345
+1.11.1
-2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With