Regular expression to find any number in a string

Searching for positive, negative, and/or decimals, you could use [+-]?\d+(?:\.\d+)?

>>> nums = re.compile(r"[+-]?\d+(?:\.\d+)?")
>>> nums.search("0.123").group(0)
'0.123'
>>> nums.search("+0.123").group(0)
'+0.123'
>>> nums.search("123").group(0)
'123'
>>> nums.search("-123").group(0)
'-123'
>>> nums.search("1").group(0)
'1'

This isn't very smart about leading/trailing zeros, of course:

>>> nums.search("0001.20000").group(0)
'0001.20000'

Edit: Corrected the above regex to find single-digit numbers.

If you wanted to add support for exponential form, try [+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?:

>>> nums2 = re.compile(r"[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?")
>>> nums2.search("-1.23E+45").group(0)
'-1.23E+45'
>>> nums2.search("0.1e-456").group(0)
'0.1e-456'
>>> nums2.search("1e99").group(0)
'1e99'

\d should be fine for matching any nonnegative integer. \d is equivalent to [0-9] (any single digit character) so of course it won't match negative numbers. Add an optional negative sign in that case:

\-?\d+

\d will definitely match 0.

Tags:

Python

Regex