Skip to content
Advertisement

Regular expression to find any number in a string

What’s the notation for any number in re? Like if I’m searching a string for any number, positive or negative. I’ve been using d+ but that can’t find 0 or -1

Advertisement

Answer

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'
Advertisement