SyntaxFix
Write A Post
Hire A Developer
Questions
Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.
But there is a simple algorithm to do this, which I described in this answer to a previous question.