Need a regular expression to match { and }.
Here is my requirement.
If the input is like
avsg{sdhsd{jh{ashdhas}hdasjhd}
…the output should be
avsgsdhsdjh{ashdhas}hdasjhd
I have to trim all the occurrences of { and } except if there is a matching } for a {.
EDIT — some further examples:
Nested brackets are not allowed. We allow ‘{‘ and ‘}’ that too only once and we remove all the brackets. Giving some more examples.
1). IN:afhad{adfh}jsdfhd OUT: afhad{adfh}jsdfhd
2). IN:afhad{a{dfh}jsdfhd OUT: afhada{dfh}jsdfhd
3). IN:afh{ad{adfh}jsdf}hd OUT:afhad{adfh}jsdfhd
4). IN:afhad{adfhjsdfhd OUT:afhadadfhjsdfhd
[^{}]*matches zero or more of any characters except{or}.\{[^{}]*\}matches an opening brace followed by a closing brace, with any number of any characters except braces between them.All together,
([^{}]*(?:\{[^{}]*\}[^{}]*)*)matches zero or more non-braces or matched pairs of braces and captures them in group #1, and then(?:[{}]|$)matches the next unpaired brace or the end of the input. Replacing the match with$1(the contents of group #1) effectively deletes the unpaired brace.