Extracting patterns after matching a regex

pdpi pdpinheiro at gmail.com
Tue Sep 8 15:15:47 CEST 2009

On Sep 8, 1:56 pm, Martin <mdeka... at gmail.com> wrote:
> Hi,
> I need to extract a string after a matching a regular expression. 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". I am not sure as to the best approach to the
> problem, I had been trying to match the string using something like
> this:
> m = re.findall(r"FTPHOST", s)
> But I couldn't then work out how to return the "e4ftl01u.ecs.nasa.gov"
> part. Perhaps I need to find the string and then split it? I had some
> help with a similar problem, but now I don't seem to be able to
> transfer that to this problem!
> Thanks in advance for the help,
> Martin

What you're doing is telling python "look for all matches of
'FTPHOST'". That doesn't really help you much, because you pretty much
expect FTPHOST to be there anyway, so finding it means squat. What you
_really_ want to tell it is "Look for things shaped like 'FTPHOST:
<ftpaddress>', and tell me what <ftpaddress> actually is". Look here:
http://docs.python.org/howto/regex.html#grouping. That'll explain how
to accomplish what you're trying to do.

More information about the Python-list mailing list