I have here a function creating code for a simple 3D list using regex to add a '],' at the end of line only if there are no triple square brackets ]]] there:
r"(?<!]])]$"
The above regex works fine on regex101, but fails to work in Python 3.9 on Linux.
Now I am curious: Why does such a simple regex not work in Python?.
I am not interested in getting this issue fixed as I can easily find a workaround myself. I am interested in an explanation how it comes that this regex doesn't work? What am I missing here and have better to know? Can you reproduce this?
Below the mentioned function:
def pprintL3D(shape=(3,3,3), verbose=False):
import math
import re
import numpy as np
reExpr1 = r"(?<=\d) (?= {0,1}\d)" # https://regex101.com/r/Obo6vs/1
reExpr2 = r"(?<!]])]$" # https://regex101.com/r/unJC1f/1
if verbose:
print( "L3D = " +
"\n ".join( re.sub(reExpr2,'],',re.sub(reExpr1, "," , strL3Dnp)).splitlines() ) )
# ---
L3D = []
for i in range(1,4):
L3D.append([])
for j in range(1,4):
L3D[i-1].append([])
for k in range(1,4):
L3D[i-1][j-1].append(9*(i-1)+3*(j-1)+k)
from pprint import pprint
return L3D # pprint(L3D)
print(pprintL3D(verbose=True))
Thanks in advance for any enlightening hints on my way to understanding how regular expressions work in Python.
P.S. I have changed the code adding re.M to the call of the re.sub() as follows:
if verbose:
print( "L3D = " +
"\n ".join( re.sub(reExpr2,'],', re.sub(reExpr1, "," , strL3Dnp), re.M).splitlines() ) )
but this didn't change the result I am getting.
Update after solving the problem using regex101 Code Generator:
I have been through many postings here on stackoverflow and through many links on Internet, but still not aware of the code generator at regex101. With screen overloaded with infos I needed a minute until I have found where should I click to change the language option and to get an example of code. I think that it would be helpful to provide this info as pictures so others can follow that advice easily too:

