re.sub() raise exception if no match to substitute

Steven Taschuk staschuk at telusplanet.net
Mon May 5 15:39:29 EDT 2003


[quoted text reflowed]

Quoth Jeff Kowalczyk:
> I'm trying to keep to an exception-driven style in a data-munging
> script I'm writing, but the re.sub() function does nothing and
> does it silently in the absence of a match to substitute against.
  [...]

That is, of course, by design.  (It makes sense if you're doing a
global search-and-replace in a text file, for example.)  Just one
of the reasons regular expressions are not always the best
solution to parsing problems.

However, the desired behaviour is easily written:

    def expect_and_replace(s, pat, repl):
        """Replace the occurrence of pat at the beginning of s with repl.
        Raises NoMatchError if s does not start with pat.
        """
        m = re.match(s, pat)
        if m is None:
            raise NoMatchError(s, pat)
        return m.expand(repl) + s[m.end():]

(Untested.)

-- 
Steven Taschuk                           staschuk at telusplanet.net
"I'm always serious, never more so than when I'm being flippant."
                            -- _Look to Windward_, Iain M. Banks





More information about the Python-list mailing list