Regex matching 3rd word in a line?

Harvey Thomas hst at empolis.co.uk
Fri Oct 31 04:28:57 EST 2003


Ian Gil
> Sent: 31 October 2003 08:46
> To: python-list at python.org
> Subject: Re: Regex matching 3rd word in a line?
> 
> 
> >> I'm looking to match the 3rd (or whatever) word in a line, 
> where word
> >> can be anything that's not white space.
> >> 
> >> I'm not programming, but I'm using a program which says it 
> uses python
> >> style regular expressions.
> >> 
> > 
> > This will match the third word in a line:
> > 
> > ^(?:\S+\s){2}(\S+)
> > 
> > Change the "2" to "whatever - 1" to match a different word.
> 
> This worked except it's matching from the beginning up to the 
> third word
> and I'm looking to match just the third word. I tried some 
> variations of
> it but apparently not the right ones.
> 
> Thanks,
> 
> Ian
> -- 
I don't know how you are doing the matching, but I guess it's using re.search.
re.search returns a match object. Using the match object's group method
group(0) returns the whole of the matched string
group(1) returns the string in the first capturing group
group(2) returns the string in the second capturing group
etc

So, if x is the match object returned, then using the RE above x.group(1) will contain the third word.

HTH

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.





More information about the Python-list mailing list