Extract all numbers

EasyRegEx Programs · 5 of 20

Write a Python program to extract integers and decimals from text.

Advertisement
Output
[-3.5, 1013.0, 82.4]

Approach

  1. -?\d+(?:\.\d+)?.

Solution

Python
import re text = "Temp -3.5C, pressure 1013 hPa, humidity 82.4%"print([float(x) for x in re.findall(r"-?\d+(?:\.\d+)?", text)])
Output
[-3.5, 1013.0, 82.4]

Line by line

Line 4

(?:...) groups the decimal part without creating a capture, so findall returns whole matches.

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Leave a Comment