New to using re. Search for a number before a string.

Jussi Piitulainen jpiitula at
Sat Nov 2 08:06:20 CET 2013

Captain Dunsel writes:

> I have a text file that has lines with numbers occasionally
> appearing right before a person's name.  For example:
> where I want to search for the name "ELMER FUDD" and extract the
> number right in front of it "608309" when such a number appears but
> the length of the number is variable and using ?<= in a regular
> expression will only search for a fixed length.
> Any ideas appreciated! 

Search for the digits and the name together. Make the digits a group
by putting their pattern in parentheses. If there is a match object,
extract the group.

 >>> m =':(\d*)ELMER FUDD$', line)
 >>> if m else 'not found'
 'not found'
 >>> m =':(\d*)FUDD, ELMER$', line)
 >>> if m else 'not found'

If you want a match only when there are digits, use \d+ instead.

Look at and here:

More information about the Python-list mailing list