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

Alex Martelli aleax at aleax.it
Mon May 5 15:51:33 EDT 2003


Jeff Kowalczyk wrote:

> 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...

You could use re.subn, and check if the second item of the 2-items tuple
it returns is 0.  Not ideal, but...


Alex





More information about the Python-list mailing list