How to escape strings for re.finditer?

Thomas Passin list1 at tompassin.net
Mon Feb 27 21:44:26 EST 2023


On 2/27/2023 9:16 PM, avi.e.gross at gmail.com wrote:
> And, just for fun, since there is nothing wrong with your code, this minor change is terser:
> 
>>>> example = 'X - abc_degree + 1 + qq + abc_degree + 1'
>>>> for match in re.finditer(re.escape('abc_degree + 1') , example):
> ...     print(match.start(), match.end())
> ...
> ...
> 4 18
> 26 40

Just for more fun :) -

Without knowing how general your expressions will be, I think the 
following version is very readable, certainly more readable than regexes:

example = 'X - abc_degree + 1 + qq + abc_degree + 1'
KEY = 'abc_degree + 1'

for i in range(len(example)):
     if example[i:].startswith(KEY):
         print(i, i + len(KEY))
# prints:
4 18
26 40

If you may have variable numbers of spaces around the symbols, OTOH, the 
whole situation changes and then regexes would almost certainly be the 
best approach.  But the regular expression strings would become harder 
to read.


More information about the Python-list mailing list