Regexdrill

Level 3: Real-world validation Exercise 45 of 88 Free

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 exercise

More exercises in Real-world validation