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

John Machin sjmachin at lexicon.net
Mon May 5 17:30:14 EDT 2003


"Jeff Kowalczyk" <jtk at yahoo.com> wrote in message news:<mailman.1052154910.11555.python-list at python.org>...
> 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. I've elected to use a few sequential regexps to pre-process and
> normalize the data before finally splitting it into lists of strings for more structured
> processing. Here's one of them, with two test cases:
> 
> s1 = r",54321,05022003,..."
> s2 = r"1234,54321,05022003,..."
> snew1 = re.sub(r"^,",'',s1)
> snew2 = re.sub(r"^,",'',s2)
> 
> very occasionally there will be a value in the first field before the comma (s2), causing
> the match to fail. I'd like to raise an exception to kick off some code handle it.
> 
> is there any elegant way to do this kind of thing without a (re.match->if no
> groups->raise->else sub) pattern? This particular case is admittedly very simple, but I'm
> interested in the general style of raising exceptions for regexp non-matches...

Have you considered using a csv module -- see e.g.
    www.object-craft.com.au/projects/csv/
 -- instead of struggling with REs?

:-)
Have you considered those in other timezones who might choke on their
breakfast upon seeing REs, "elegant" and "style" in the same posting?
(-:




More information about the Python-list mailing list