Back to Home

Integer Validation Regex (Positive or Negative)

CronOS Team
regexintegervalidationtutorialnumber

Need to generate a regex pattern?

Use CronOS to generate any regex pattern you wish with natural language. Simply describe what you need, and we'll create the perfect regex pattern for you. It's completely free!

Generate Regex Pattern

Integer Validation Regex (Positive or Negative)

Validate integers that can be positive, negative, or zero using a simple regex pattern with optional minus sign.

Pattern Breakdown

regex
^-?\d+$

Components

ComponentDescriptionMatches
^Start anchorEnsures match from string start
-?Optional minusOptional minus sign
\d+One or more digitsInteger digits
$End anchorEnsures match to string end

Character Classes

  • -? - Optional minus sign (zero or one occurrence)
  • \d - Any digit (0-9)
  • + - Quantifier: one or more occurrences

Examples

Valid:

  • 0
  • 123
  • -123
  • 999999
  • -1000000

Invalid:

  • 12.5 (decimal)
  • +5 (plus sign)
  • 123 (leading space)
  • 123 (trailing space)
  • - (just minus sign)
  • abc (non-numeric)

Implementation

JavaScript

javascript
const integerRegex = /^-?\d+$/;
integerRegex.test('123'); // true
integerRegex.test('-123'); // true
integerRegex.test('0'); // true
integerRegex.test('12.5'); // false (decimal)
integerRegex.test('+5'); // false (plus sign)

Python

python
import re
integer_regex = r'^-?\d+$'
bool(re.match(integer_regex, '123'))  # True
bool(re.match(integer_regex, '-123'))  # True
bool(re.match(integer_regex, '0'))  # True
bool(re.match(integer_regex, '12.5'))  # False (decimal)

Go

go
integerRegex := regexp.MustCompile(`^-?\d+$`)
integerRegex.MatchString("123") // true
integerRegex.MatchString("-123") // true
integerRegex.MatchString("0") // true
integerRegex.MatchString("12.5") // false (decimal)

Limitations

  1. Includes zero: Matches 0 (and -0)
  2. No leading zeros: Accepts 0123 (may want to prevent this)
  3. No size limit: Doesn't enforce maximum/minimum value
  4. String validation: Validates string format, not actual integer type
  5. No scientific notation: Doesn't support 1e5 format

When to Use

  • Integer input validation (any sign)
  • General number input forms
  • When you need flexible integer validation
  • Form input validation
  • Quick integer format checking

For production, consider:

  • Preventing leading zeros: ^-?(0|[1-9]\d*)$
  • Adding value range validation
  • Converting to integer type after validation
  • Handling edge cases for very large numbers
  • Supporting plus sign if needed: ^[+-]?\d+$

Need to generate a regex pattern?

Use CronOS to generate any regex pattern you wish with natural language. Simply describe what you need, and we'll create the perfect regex pattern for you. It's completely free!

Generate Regex Pattern