Regex patterns/Numbers

Whole number

The smallest useful validator — and a reminder of what the anchors are doing.

/^-?\d+$/
Open it in Rex

The problem

Check that a string holds a whole number, optionally negative, and nothing else.

How it reads

start-skip\drepeatend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^-?\d+$In order:
  2. ^The start of the text (or of a line with the m flag)
  3. -?The character "-", optionally (zero or one time)
  4. \d+A digit, one or more times, as many as possible
  5. $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.

More numbers patterns