Advertisement

Pattern library / Extract & Replace

Regex to Extract Numbers from a String

Almost every data-cleanup task hits the same wall: text like "total: 1,249.50 USD" where you need 1249.50. Regex solves it by matching the number shape and capturing it — the patterns below scale from “any integer” to “signed decimal with separators”, each with the exact use case it fits.

The pattern
[-+]?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?
Load this pattern into the tester →

How the pattern works

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
order total: 1,249.50 USDMatchthousands + decimal capturedTry →
-42Matchsigned integerTry →
temp +98.6FMatchexplicit plus signTry →
v1.2.3 releaseMatchmatches 1.2 then .3 — see pitfallsTry →
no digits hereNo matchnothing to extractTry →
1234Matchplain 4-digit int (groups optional)Try →

Where to use it

JavaScript (capture all)

const s = 'total: 1,249.50 USD, tax 124.50';
const nums = s.match(/[-+]?[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?/g)
  .map(x => Number(x.replace(/,/g, '')));  // [1249.5, 124.5]

Python (findall + clean)

import re
nums = re.findall(r'[-+]?[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?', 'total: 1,249.50 USD')
values = [float(n.replace(',', '')) for n in nums if n]

Bash (strip everything but numbers)

echo 'total: 1,249.50 USD' | grep -oE '[-+]?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?'

Common mistakes

Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
Open the regex tester →

FAQ

How do I extract only whole numbers?

Use [-+]?\b[0-9]+\b — it ignores decimal fragments and avoids digits glued to letters.

How do I convert the extracted text to a number?

Strip separators first: Number(x.replace(/,/g, '')) in JS, float(x.replace(',', '')) in Python. Regex finds the shape; parsing makes it a value.

Why do I get [''] in my matches?

With the global flag, optional groups can match empty strings at every position. Filter empties: .filter(Boolean) in JS or [n for n in nums if n] in Python.

Extract Domain from URL — Regex Capture Group · Remove Query Parameters with Regex (Replace Example) · IPv4 Address Regex — Validate Dots & Octets

For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.