CSharp · Console
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
private static string GetJsFile(string filename) {
return @"function test1() {
return 'OK';
}
function test2(x) {
if (x == 2) {
return 'OK';
}
}
function test3(x,y) {
var x = '}`\'}';
var r = /}/;
// }
/* }
}
*/
}
function test4() {
}";
}
private static string GetFunction(string jstext, string functionname) {
var start = Regex.Match(jstext, @"function\s+" + functionname + @"\s*\([^)]*\)\s*{");
if(!start.Success) {
throw new Exception("Function not found: " + functionname);
}
StringBuilder sb = new StringBuilder(start.Value);
jstext = jstext.Substring(start.Index + start.Value.Length);
var brackets = 1;
var i = 0;
var delimiters = "`/'\"";
string currentDelimiter = null;
var isEscape = false;
var isComment = false;
var isMultilineComment = false;
while(brackets > 0 && i < jstext.Length) {
var c = jstext[i].ToString();
var wasEscape = isEscape;
if(isComment || !isEscape)
{
if(c == @"\") {
// Found escape symbol.
isEscape = true;
} else if(i > 0 && !isComment && (c == "*" || c == "/") && jstext[i-1] == '/') {
// Found start of a comment block
isComment = true;
isMultilineComment = c == "*";
} else if(c == "\n" && isComment && !isMultilineComment) {
// Found termination of singline line comment
isComment = false;
} else if(isMultilineComment && c == "/" && jstext[i-1] == '*') {
// Found termination of multiline comment
isComment = false;
isMultilineComment = false;
} else if(delimiters.Contains(c)) {
// Found a string or regex delimiter
currentDelimiter = (currentDelimiter == c) ? null : currentDelimiter ?? c;
}
// The current symbol doesn't appear to be commented out, escaped or in a string
// If it is a bracket, we should treat it as one
if(currentDelimiter == null && !isComment) {
if(c == "{") {
brackets++;
}
if(c == "}") {
brackets--;
}
}
}
sb.Append(c);
i++;
if(wasEscape) isEscape = false;
}
return sb.ToString();
}
public static void Main()
{
var fileContent = GetJsFile("somefile.js");
for(var i = 1; i < 5; i++) {
Console.WriteLine(GetFunction(fileContent, "test" + i));
Console.WriteLine("-----------------------------------");
}
}
}