regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match an Integer

Copy the pattern, paste your text below, and see every whole number it finds. Below the tester: how to keep it from matching parts of decimals, and how to require a full-string match.

/ /

What this pattern matches

This expression matches whole numbers, positive or negative: 42, -7, 1000. It uses word boundaries so it grabs complete numbers rather than random digits inside longer tokens.

How it works, part by part

-? — an optional leading minus sign.

\b — a word boundary so the match starts at the beginning of a number.

\d+ — one or more digits.

\b — a closing word boundary.

Integers inside decimals

In free text, 3.14 contains the integers 3 and 14, and this pattern will match both. If you want only standalone integers and not the pieces of a decimal, use a lookahead like -?\b\d+\b(?!\.\d). To validate that an entire string is a single integer, anchor it: ^-?\d+$.

Use it in your code

Python
import re
text = "Order 42 units at -7 discount, total 1000. A decimal 3.14 has an integer part 3 and 14."
pattern = r'''-?\b\d+\b'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "Order 42 units at -7 discount, total 1000. A decimal 3.14 has an integer part 3 and 14.";
const re = new RegExp(String.raw`-?\b\d+\b`, "g");
console.log(text.match(re));

FAQ

Does it match a leading plus sign like +5?

No. Change -? to [-+]? to allow an optional plus or minus.

Why does it match 3 and 14 inside 3.14?

It only knows digits and word boundaries, not decimal points. Add (?!\.\d) to skip integers that are part of a decimal.

How do I require the whole string to be an integer?

Anchor it with ^-?\d+$ so nothing but an integer is allowed from start to end.