Next / Previous / Contents / TCC Help System / NM Tech homepage

9.17. parseRe(): Parse a regular expression

A service routine used anywhere you want to match a regular expression at the start of a string.

sidereal.py
# - - -   p a r s e R e

def parseRe ( s, regex, message ):
    """Parse a regular expression at the head of a string.

      [ (s is a string) and
        (regex is a compiled regular expression) and
        (message is a string describing what is expected) ->
          if  s starts with a string that matches regex ->
            return (head, tail) where head is the part of s
            that matched and tail is the rest
          else ->
            raise SyntaxError, "Expecting (message)" ]
    """

    #-- 1 --
    # [ if the head of s matches regex ->
    #     m  :=  a match object describing the matching part
    #   else -> raise SyntaxError, "Expecting (message)" ]
    m  =  regex.match ( s )
    if  m is None:
        raise SyntaxError, "Expecting %s: '%s'" % (message, s)

The match instance m has a method .group() that returns the matched text. The m.end() method returns the position just past the matched text.

sidereal.py
    #-- 2 --
    # [ return (matched text from s, text from s after match) ]
    head  =  m.group()
    tail  =  s[m.end():]
    return  (head, tail)