Regex matching 3rd word in a line?
Harvey Thomas
hst at empolis.co.uk
Fri Oct 31 07:03:52 EST 2003
Klaus-G. Meyer
> Ian Gil wrote:
> > and I'm looking to match just the third word.
>
> Hm, first extract the third word and then use re?
>
> >>> s = "one two three four"
> >>> s.split()[2]
> 'three'
>
> split has an optional argument "sep" to define other chars than
> whitespace characters.
>
> --
> Gruß - regards
> Klaus :-)
Agreed, using the split method of string is best for the problem as originally posed, but if you change the definition of a word to be one or more alphanumeric characters, the best method is surely to use something like
>>> a = 'qqq www eee rrr'
>>> r = re.compile('^(?:\w+\W+){2}(\w+)')
>>> q = r.match(a)
>>> q.group(1)
'eee'
_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.
More information about the Python-list
mailing list