This is a fairly common task. The easiest way I know to handle this:
^[+-]?(\d*\.)?\d+$
There are other complications, for example, whether you want to resolve leading zeros or commas or something like that. It can be as hard as you want it to be. For example, if you want to allow the format 1,234,567.89, you can go with this:
^[+-]?(\d*|\d{1,3}(,\d{3})*)(\.\d+)?\b$
This \b is a word break, but I use it as a hidden way to require at least one digit at the end of a line. So an empty string or one + will not match.
However, keep in mind that regular expressions are not an ideal way to parse numeric strings. . All modern programming languages ββthat I know of have quick, simple, built-in methods for this.
Justin morgan
source share