Regular Exp

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Fri Oct 31 03:39:14 EST 2003


On Fri, 31 Oct 2003 08:11:39 GMT, afds wrote:
> If I want to match $.58 in $.589922 How do I do it with Regular Expressions?
> 
> >>> s=re.search("\$\.[0-9]{2}", "$.589922")
> >>> s.string
> '$.589922'

Yes.  The 'string' member of a MatchObject returns the entire string
that was passed to the search() that produced it, as the docs will tell
you:

    <http://www.python.org/doc/current/lib/match-objects.html#l2h-875>

> and not
> '$.58' which i s what I want

You need to define one or more groups within the expression, grouping
what you want to access.  Then use 'MatchObject.group()' to access one
group at a time or 'MatchObject.groups()' to access all of them as a
tuple:

    >>> s = re.search( "(\$\.[0-9]{2})", "$.589922" )
    >>> s.group(1)
    '$.58'
    >>> s.groups()
    ('$.58',)
    >>>

-- 
 \          "I used to be a proofreader for a skywriting company."  -- |
  `\                                                     Steven Wright |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list