I have many strings where I'm trying to selectively replace all instances of f[--whatever--]
with f.__getitem__(--whatever--, x=x)
.
This is the last option left to me to patch some old complicated code using eval
calls that I'm unfortunately stuck with.
It's easy to replace the f[
, but it's hard to know whether instances of ]
are associated with this pattern or some other
miscellaneous patterns like lists [--whatever--]
or indexing .loc[--whatever--].
There are no isolated cases of ]
that are not part of a full []
in my strings.
My latest attempt at a solution uses regex: 1) sub ([^f])[(.+?)] with \1openbracket\2closebracket to preserve [] that isn't part of f[] 2) the remaining [] 3) sub back openbracket & closebracket with []
The problem is that this doesn't handle many nested cases like the example below. I'm looking for a more comprehensive solution to establish whether a given ]
is associated with f[]
or some other structure. Is there a way to do this with pyparsing
or some other module?
Example
f[r@ndom t3xt] + [some r@ndom t3xt] + [f[more r@ndom t3xt] / f[more t3xt]] + [f[f[more t3xt] + 3]]
should become
f.__getitem__(r@ndom t3xt, x=x) + [some r@ndom t3xt] + [f.__getitem__(more r@ndom t3xt, x=x) / f.__getitem__(more t3xt, x=x)] + [f.__getitem__(f.__getitem__(more t3xt) + 3)]