Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with a very simple regex

Tags:

python

regex

I am using python to try to write some simple code that looks through strings with regular expressions and finds things. In this string:

and the next nothing is 44827

I want my regex to return just the numbers.

I have set up my python program like this:

buf = "and the next nothing is 44827"
number = re.search("[0-9]*", buf)
print buf
print number.group()

What number.group() returns is an empty string. However, when the regex is:

number = re.search("[0-9]+", buf)

The full number (44827) is properly extracted. What am I missing here?

like image 682
Eric S Avatar asked Dec 02 '22 00:12

Eric S


1 Answers

The problem is that [0-9]* matches zero or more digits, so it is more than happy to match to a zero-length string.

Meanwhile, [0-9]+ matches one or more digits, so it needs to see at least one number in order to catch.


you might want to use findall and handle the case in which you have multiple numbers per line.

like image 134
Donald Miner Avatar answered Dec 06 '22 08:12

Donald Miner