Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to find any number in a string

Tags:

python

regex

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

like image 821
Takkun Avatar asked Jun 28 '11 14:06

Takkun


People also ask

How do you find digits in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

What is the regex for anything?

(wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.

How do I extract a specific number from a string in Python?

Summary: To extract numbers from a given string in Python you can use one of the following methods: Use the regex module. Use split() and append() functions on a list. Use a List Comprehension with isdigit() and split() functions.


1 Answers

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'
like image 199
Greg Haskins Avatar answered Sep 29 '22 17:09

Greg Haskins