Decimal numbers
A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.
The task
The whole line must match. Match a number: an optional minus sign, then 0 or a whole part with no leading zeros, then optionally a period followed by one or more digits. So -12.5, 0.25 and 7 match, but 007, .5 and 3. do not.
What this exercise teaches
-?(?:0|[1-9]\d*)(?:\.\d+)? handles each rule in turn. The alternation 0|[1-9]\d* is the standard way to forbid leading zeros while still allowing a lone 0, and making the period part of the optional group rules out a trailing period.
A hint if you get stuck
The whole part is an alternation: either a single 0, or a digit from 1 to 9 followed by any digits. The decimal part is an optional group.
Try it now, free, no account needed
Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Real-world validation
- US ZIP and ZIP+4Free
- US phone number formatsFree
- Dates YYYY-MM-DDFree
- 24-hour times HH:MMFree
- 12-hour times with AM or PMFree
- Simple email addressesFree
- Web addressesFree
- Hex colorsFree
- IPv4 addresses, 0 to 255Free
- URL slugsFree
- UsernamesFree
- SKU codesFree
- Card numbers in groups of fourFree
- Currency amounts with commasFree
- Semantic versionsFree
- MAC addressesFree
- UUIDsFree
- Percentages from 0 to 100Free
- ISO 8601 timestampsFree