How to escape strings for re.finditer?

Grant Edwards grant.b.edwards at gmail.com
Wed Mar 1 12:04:08 EST 2023


On 2023-02-28, Cameron Simpson <cs at cskk.id.au> wrote:

> Regexps are:
> - cryptic and error prone (you can make them more readable, but the 
>    notation is deliberately both terse and powerful, which means that 
>    small changes can have large effects in behaviour); the "error prone" 
>    part does not mean that a regexp is unreliable, but that writing one 
>    which is _correct_ for your task can be difficult,

The nasty thing is that writing one that _appears_ to be correct for
your task is often fairly easy. It will work as you expect for the
test cases you throw at it, but then fail in confusing ways when
released into the "real world". If you're lucky, it fails frequently
and obviously enough that you notice it right away. If you're not
lucky, it will fail infrequently and subtly for many years to come.

My rule: never use an RE if you can use the normal string methods
(even if it takes a a few lines of code using them to replace a single
RE).

--
Grant


More information about the Python-list mailing list