Regex to Match Integers

Match positive and negative integers with this regex. Validates whole numbers including optional negative sign. Free regex tester tool.

Regular Expression

/^-?\d+$/

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
-Matches the literal character '-'
?Makes the preceding element optional (zero or one times)
\dMatches any digit (0-9)
+Matches the preceding element one or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex matches integer values, both positive and negative. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string. This ensures the entire string must be an integer, not just a substring.

-? — Matches an optional minus sign. The ? quantifier makes the hyphen optional, so both positive numbers like 42 and negative numbers like -7 are matched.

\d+ — Matches one or more digits. The \d shorthand is equivalent to the character class [0-9]. The + quantifier requires at least one digit, so an empty string or a lone minus sign will not match.

$ — Anchors the match at the end of the string. Combined with the ^ anchor, this ensures the entire input must be a valid integer.

This is one of the simplest and most commonly used regex patterns. It validates that a string contains only an optional negative sign followed by digits. Note that this pattern does allow leading zeros (e.g., '007' would match). If you need to disallow leading zeros, you could modify the pattern to ^-?(?:0|[1-9]\d*)$. The pattern also does not set a maximum number of digits, so very large numbers that exceed programming language integer limits would still match the regex. For strict numeric validation, combine this regex check with a numeric range check in your application code.

Example Test Strings

InputExpected
42Match
-17Match
3.14No Match
0Match
12abcNo Match

Try It — Interactive Tester

//
gimsuy
No matches found.
Pattern: 7 charsFlags: noneMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →