Watt Watt - 2 months ago 13
Python Question

Find Regex pattern to match innermost (first) pattern out of bigger pattern

My test string is like this

sdfsdfs sdfsd
To(SObj,sfddslfks
To(SObj,
abc
),
abc(_)
)
))
),
To(SObj,
Or(
And(
Or(
And(
abc
Or(
DCh=t'3',
abc
ab3
)
),
To(SObj, sfdsd
sdfdsf
)
)


note: In real string all parenthesis are balanced

I want to write a regex pattern to remove (or match) only
To(SObj
which contains
DCh
in it.

i.e. From above example, only below needs to be removed or matched

To(SObj,
Or(
And(
Or(
And(
abc
Or(
DCh=t'3',
abc
ab3
)
),


But, my pattern
(To\(SObj[\s\S]+DCh[\s\S]+)To\(SObj
matches entire test string

Answer

Without balansing the brackets :

resultstring = re.sub(r'To\(SObj,[^)]*?DCh=[^(]*\),','', inputstring, flags=re.DOTALL)

Can test the regex here