Saturday, March 13, 2010

Regular Expression for inserting codes at the end of a function

This is a regular expression that i used to insert codes at the end of a function, the original code was created for actionscript 3, and you tweak it a  little to match your language, that is if its a C-based language.

reg  = "("+funcName+"\\([\\s\\S]*?\\)[\\s\\S]*?{[\\s\\S]*?)(?=(})[\\s\\S]*?((protected override|private|public) function))";

re = new RegExp(reg);
newCode = oldCode.replace(re, "$1 " + code);

The regular expression is
(yourFunc([\s\S]*?)[\s\S]*?{[\s\S]*?)(?=(})[\s\S]*?((protected override|private|public) function))

Explanation
(yourFunc([\s\S]*?)[\s\S]*?{[\s\S]*?)
First it finds the function named yourFunc followed by (
Then finds the arguements but stop finding mor, the *?, once it finds the first )
Then it continues to find anything, in as3 this is the : thing, and stops after it finds {
Lastly it finds everything after {, literally everything till the last one and to stop it you have to see the next pattern

(?=(})[\\s\\S]*?((protected override|private|public) function))
First it excludes to include on the results the following results it would find, the ?=
This exclusion starts with } followed by anything, \s\S until it finds the next function declaration.

The groupings
We grouped the results into 2 big groups and since we need everything that came before }, we group the regular expression before it into a big group so that once we substitute we could just use $1 to get all of them back.

Its so hard to explain this stuff on writing and i suggest you to just test them and comment if there is something wrong or there are some area where the regular expression could be enhance. Thanks