Use re.findall() with a regex pattern tailored to the number format you need—such as re.findall(r"\d+", text) for non-negative integers or re.findall(r"-?\d+(?:\.\d+)?", text) for signed integers and decimals—and convert the matched strings with [int(x) for x in ...] or [float(x) for x in ...].
Basic Example
import re
text = "Order #402: 3 laptops at $1,250.50 each, discount -15%."
# 1. Extract all non-negative integer sequences as ints
integers = [int(n) for n in re.findall(r"\d+", text)]
print(integers) # Output: [402, 3, 1, 250, 50, 15]
# 2. Extract signed integers AND decimal numbers as floats
numbers = [float(n) for n in re.findall(r"-?\d+(?:\.\d+)?", text)]
print(numbers) # Output: [402.0, 3.0, 1.0, 250.5, -15.0]
# 3. Extract ONLY standalone whole numbers (ignoring digits embedded in words like 'v2' or 'item42')
standalone = [int(n) for n in re.findall(r"\b\d+\b", "v2 has 10 items and 25 errors")]
print(standalone) # Output: [10, 25]
Key Details & Edge Cases
- Beware of
\dmatching non-ASCII Unicode digits (²,٣,५): In Python 3,\dmatches any Unicode decimal digit (such as Arabic-Indic٣or superscript²), which can causeint("²")to raiseValueError: invalid literal for int() with base 10. Restrict matching to ASCII digits0–9using[0-9]+or passingflags=re.ASCII(re.findall(r"\d+", text, flags=re.ASCII)). - Handling comma-separated thousands (
1,250.50): Standard\d+(?:\.\d+)?splits"1,250.50"into["1", "250.50"]. Match formatted numbers cleanly and strip commas before converting:raw_matches = re.findall(r"-?\d{1,3}(?:,\d{3})*(?:\.\d+)?|-?\d+(?:\.\d+)?", "Total: $1,250.50 and -42") values = [float(m.replace(",", "")) for m in raw_matches] print(values) # Output: [1250.5, -42.0] - Handling scientific notation (
1.5e-4,3E+8) and leading-dot decimals (.75): User"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?"when parsing logs, sensor output, or scientific text containing exponents or.5style floats. - Avoid capturing groups
(...)without?:inre.findall(): If you writere.findall(r"-?\d+(\.\d+)?", "12.5 and 7"),re.findall()returns only the captured group (['.5', '']) instead of the full match. Always use a non-capturing group(?:...)(r"-?\d+(?:\.\d+)?"). - Simple space-separated integers without regex (
str.isdigit()): If your string consists solely of whitespace-delimited tokens (e.g.,"10 apples and 25 oranges"), a list comprehension works withoutre, though it misses attached punctuation ("25.") and negative signs ("-5"):nums = [int(tok) for tok in "10 apples and 25 oranges".split() if tok.isdigit()]
Regex Pattern Reference for Number Extraction
| Target Number Format | Regex Pattern | Example Input | Extracted Output |
|---|---|---|---|
| Non-negative integers | r"[0-9]+" |
"ID 42, qty 7" |
['42', '7'] |
| Standalone integers only | r"\b[0-9]+\b" |
"box2 has 15 kg" |
['15'] (skips box2) |
| Signed integers & decimals | r"-?[0-9]+(?:\.[0-9]+)?" |
"temp -4.5C, high 12" |
['-4.5', '12'] |
| Thousands-separated numbers | r"-?[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?" |
"$12,450.75" |
['12,450.75'] |
| Scientific / engineering notation | r"[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?" |
"val=1.2e-5, .5" |
['1.2e-5', '.5'] |
You must log in or register to comment.
