Extracting patterns after matching a regex

Terry Reedy tjreedy at udel.edu
Tue Sep 8 09:40:09 EDT 2009


Mart. wrote:
> On Sep 8, 2:15 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
>> Martin wrote:
>>> Hi,
>>> I need to extract a string after a matching a regular expression.

Whether or not you need re is an issue to be determined.

 >>> For example I have the string...
>>> s = "FTPHOST: e4ftl01u.ecs.nasa.gov"
>>> and once I match "FTPHOST" I would like to extract
>>> "e4ftl01u.ecs.nasa.gov".

Just split the string on ': ' and take the second part.
Or find the position of the space and slice the remainder.

> so the .* means to match everything after the regex? That doesn't help
> in this case

It helps in the case you presented.

 > as the string is placed amongst others for example.

> MEDIATYPE: FtpPull\r\n', 'MEDIAFORMAT: FILEFORMAT\r\n', 'FTPHOST:
> e4ftl01u.ecs.nasa.gov\r\n', 'FTPDIR: /PullDir/0301872638CySfQB\r\n',
> 'Ftp Pull Download Links: \r\n',

What you show above is a tuple of strings. Scan the members looking for 
s.startswith('FTPHOST:') and apply previous answer.
Or if above is actually meant to be one string (with quotes omitted), 
split in ',' and apply previous answer.

tjr




More information about the Python-list mailing list