Skip to main content
hank-builds.com

Positive Integer regex

Matches positive integers (no leading zeros, no negatives).

/(?<![-\d])[1-9]\d*\b/g

What it matches

One or more digits starting with 1-9, so no leading zeros, with a lookbehind that refuses to start immediately after a minus sign or another digit. That is what stops it returning the 5 in -5 or the 7 in 007, both of which a plain \d+ would happily match.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

(?<!...) [-\d] [1-9] \d \b

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
[-\d]Match one of: Literal "-", Digit (0-9)
[1-9]Match one of: Literal "1"–Literal "9"
\d*Digit (0-9), zero or more
\bWord boundary

Test cases

Matches

  • 42
  • 1
  • 100

Does not match

  • 0
  • -5
  • 007

Caveats

Zero itself does not match, by design. JavaScript has supported lookbehind since ES2018 and it is in every current browser, but older Safari and several other regex flavours reject the syntax outright, so if the pattern has to be portable, filter the results in code instead.

More numbers patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.