Python Forum

Full Version: Regular expression: cannot find 1st number in a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

Here is test string:
aaa = '   2jhjh 890 jjk'
Here is how I try to find 1st number in aaa (2 in this case):
bbb = re.match('\d', aaa)
What I finally get:
Output:
>>> type(bbb) <class 'NoneType'>
Any suggestions ?

Thanks.
Here is a solution using search:

bbb = re.search('\d', aaa).group()
So, match can't be used for this task ?
Correct. Let's look at the description of match.

Quote:match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a Match object, or None if no match was found.

match() is as if your pattern has an implicit ^ anchoring to the beginning of the string. search() doesn't and can look elsewhere in the string.