Regex patterns/Numbers
Whole number
The smallest useful validator — and a reminder of what the anchors are doing.
/^-?\d+$/The problem
Check that a string holds a whole number, optionally negative, and nothing else.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
^-?\d+$In order:^The start of the text (or of a line with the m flag)-?The character "-", optionally (zero or one time)\d+A digit, one or more times, as many as possible$The end of the text (or of a line with the m flag)
Matches
- 42
- -17
- 0
- 000
Does not match
- 3.14
- 12abc
- an empty string
- +5
- 42
Where it bites
- Drop the anchors and the pattern finds a number *inside* anything — "abc12def" would pass. The anchors are the validation.
- A leading + is rejected, as is surrounding whitespace. Trim first if that matters.
- It happily accepts numbers too large for a JavaScript number; parse and range-check separately.