Regex to extract numbers from text
This pattern finds every number in a block of text, including negative numbers and decimals. It is the quickest way to pull prices, quantities and measurements out of a sentence.
The pattern
/-?\d+(?:\.\d+)?/gThe tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.
How it works
-?- An optional minus sign.
\d+- One or more digits for the whole part.
(?:\.\d+)?- An optional decimal point followed by more digits.
Examples
Matches
42-73.141000
Does not match
no digits hereabc.
Use it in JavaScript
const text = 'Bought 3 items for 49.99, refund -5';
const nums = text.match(/-?\d+(?:\.\d+)?/g) ?? [];
// ['3', '49.99', '-5']
const total = nums.map(Number).reduce((a, b) => a + b, 0);
// Just the digits, joined together
const digits = text.replace(/\D/g, '');Limits and tips
- Numbers with thousands separators such as 1,000 are returned as two matches (1 and 000). Remove the commas first with text.replace(/,/g, "").
- A hyphen between numbers, as in 10-20, is read as a minus sign on the second number. Drop -? if you only need unsigned values.
- A number written like .5 is returned as 5. Use -?(?:\d+\.?\d*|\.\d+) if you need to keep those.
- The result is an array of strings. Convert with .map(Number) before doing arithmetic.
Frequently asked questions
How do I get only the digits from a string?
Use text.replace(/\D/g, ""), which deletes every non-digit. Use this extraction pattern when you want each separate number instead.
How do I sum all numbers in a string?
Match them with this pattern, map the results through Number and add them with reduce.