A service routine used anywhere you want to match a regular expression at the start of a string.
# - - - 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.
#-- 2 --
# [ return (matched text from s, text from s after match) ]
head = m.group()
tail = s[m.end():]
return (head, tail)