For example I have below text
some {}} outside, and some inside $aa{bb}cc{{dd}ee}ff$, and some more $aa{bb}cc{{dd}ee}ff$ here.
I call $
flag symbol, and now I want to replace all {
or }
between pairs of $...$
using regex.
The only way I can think of is to replace multiple times, using regex
(\$.*?)(\{|\})
each time it replaces a {
or }
inside $...$
. After enough time of replacement, we got
some {}} outside, and some inside $aabbccddeeff$, and some more $aabbccddeeff$ here.
The drawback is that you don't know how many times it needs to get {
or }
completely replaced, and it apparently not efficient at all.
So I am wondering, is regex capable to doing this in a single run? For regex flavor I mean perl compatible. But if perl can not do this, I would love to know if other regex flavor can do.
Try this regex:
[{}](?=[^$]*\$(?:(?:[^$]*\$){2})*[^$]*$)
Replace each match with a blank string.
Explanation:
[{}]
- matches either {
or }
(?=[^$]*\$(?:(?:[^$]*\$){2})*[^$]*$)
- positive lookahead to make sure that the above match is followed by odd number of $
somewhere later in the string. This would make sure that {
or }
is followed by 1 or 3 or 5 or 7... instances of $
somewhere later in the string.