Number Validation Regular Expressions
Numbers can be validated in various formats including integers, decimals, and floating-point numbers. These regex patterns provide validation for common number formats, supporting both positive and negative values.
Integer Numbers
Validates whole numbers, both positive and negative, without decimal points.
Explanation
^- Start of the string.-?- Optional minus sign for negative numbers.\d+- One or more digits.$- End of the string.
Implementation
Test Cases
| Number | Valid |
|---|---|
| 123 | |
| -456 | |
| 0 | |
| -0 | |
| 1000000 | |
| 12.34 | |
| 12.0 | |
| abc | |
| 12a | |
| (empty string) | |
| +123 | |
| 1,234 | |
| 1 234 | |
| --123 |
Decimal Numbers
Validates decimal numbers with optional fractional parts, both positive and negative.
Explanation
^- Start of the string.-?- Optional minus sign for negative numbers.\d+- One or more digits before the decimal point.(\.\d+)?- Optional decimal part: a dot followed by one or more digits.$- End of the string.
Implementation
Test Cases
| Number | Valid |
|---|---|
| 123 | |
| 123.45 | |
| -456 | |
| -456.78 | |
| 0 | |
| 0.0 | |
| -0.5 | |
| 1000000.999 | |
| abc | |
| 12a | |
| (empty string) | |
| +123.45 | |
| 1,234.56 | |
| 1 234.56 | |
| .5 | |
| 123. | |
| 12.34.56 |
Notes
- These patterns do not accept numbers with leading plus signs (+). Modify the pattern to
^[+-]?\\d+$to allow both + and −. - Leading zeros are allowed (e.g., "0123" is valid). To disallow leading zeros, use a more complex pattern.
- These patterns do not support scientific notation (e.g., 1.23e10). Use a different pattern for that format.
- Thousands separators (commas, spaces) are not supported. Preprocess input to remove them if needed.
- For positive-only numbers, use
^\\d+$(integers) or^\\d+(\\.\\d+)?$(decimals). - These regex patterns validate format only. For range validation, use additional logic after regex matching.
- For specialized number patterns, see: phone numbers, credit card numbers, social security numbers, ISBN, and ZIP codes.