Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for integer
Regex pattern · validation

Regex for integer

Regex for integer: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^-?\d+$/ as an integer regex. It matches "0" and "42", and rejects "4.2" and "1e5". Leading zeros (007) are accepted.

Last updated · Maintained by FreeAIToolz · How we test

/^-?\d+$/
  • 0matches
  • 42matches
  • -17matches
  • 1000000matches
  • 4.2no match
  • 1e5no match
  • +5no match
  • 42no match
  • 1,000no match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^-?optional minus sign
\d+$one or more digits

Examples

InputResult
0✓ Matches
42✓ Matches
-17✓ Matches
1000000✓ Matches
4.2✗ No match
1e5✗ No match
+5✗ No match
42✗ No match
1,000✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Leading zeros (007) are accepted. Use ^-?(?:0|[1-9]\d*)$ to forbid them, and ^[+-]?\d+$ to allow a plus sign.

When to use this pattern

Quantity and ID fields, query parameters and CSV columns.

Use it in your language

JavaScript

const re = /^-?\d+$/;
re.test(input); // true or false

Python

import re
pattern = re.compile(r'^-?\d+$')
bool(pattern.search(value))

PHP

$ok = preg_match('~^-?\\d+$~', $value) === 1;

Java

Pattern pattern = Pattern.compile("^-?\\d+$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^-?\d+$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for integer?
/^-?\d+$/. Leading zeros (007) are accepted. Use ^-?(?:0|[1-9]\d*)$ to forbid them, and ^[+-]?\d+$ to allow a plus sign.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abc0xyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.