/// <summary> /// 解析代码并格式化,返回出错行,返回-1则为无错 /// </summary> int ParsingCode(string codeFilePath) { Regex regex = new Regex(@"\r*\n* *#+.*\r*\n"); string noCommentStr = regex.Replace(codeContent, "\n"); string[] lineStr = Regex.Split(noCommentStr, @"\n"); for (int i = 0; i < lineStr.Length; i++) { lineStr[i] = new Regex(@"\s*#+.*\r*\n*").Replace(lineStr[i], "\n"); Console.WriteLine(lineStr[i]); } //删除空字符串数组 lineStr = lineStr.Where(s => !string.IsNullOrEmpty(s.Trim())).ToArray(); Stack <char> stack = new Stack <char>(); for (int i = 0; i < lineStr.Length; i++) { //去掉尾部空行 lineStr[i] = lineStr[i].TrimEnd(); lineStr[i] = Regex.Replace(lineStr[i], @" *= *{ *\n*", " = {\n"); lineStr[i] = Regex.Replace(lineStr[i], @" *\n*} *\n*", "\n}\n"); //获取匹配字符串数组,复制下来加上回车,删除之前的旧字符串不就好了 for (int stackIndex = 0; stackIndex < lineStr[i].Length; stackIndex++) { switch (lineStr[i][stackIndex]) { case '{': stack.Push(lineStr[i][stackIndex]); //找到括号且无开始行,设置开始行 if (codeStartLine == -1) { codeStartLine = i; } break; case '}': if (stack.Count > 0 && stack.Pop() == '{') { //完全匹配,且有开始行 if (stack.Count == 0 && codeStartLine > -1) { codeEndLine = i; string ec = ""; while (codeStartLine <= codeEndLine) { ec += lineStr[codeStartLine] + "\n"; codeStartLine++; } countryEvent.Add(ec); codeStartLine = -1; codeEndLine = -1; } break; } else { return(i); } default: continue; } } //当前行没有括号且正在匹配括号为0 if (!Regex.IsMatch(lineStr[i], @"{+") && !Regex.IsMatch(lineStr[i], @"}+")) { //该行没有括号且正在匹配括号为0 if (stack.Count == 0) { countryEvent.Add(lineStr[i] + "\n"); } } } if (stack.Count == 0) { editorManager.Clear(); string str = ""; foreach (var item in countryEvent) { str += item + "\n"; } editorManager.LoadDataString(str, codeFilePath); //解析为YAML OperationInterface.SetStatusText("解析代码中,请稍后……"); var yaml = TxtResolveToYaml(codeFilePath); //editorManager.LoadDataString(yaml, codeFilePath); OperationInterface.SetStatusText("解码为YAML成功!"); mainWindow.modClassTree.Items.Clear(); new YAMLForm(Path.GetDirectoryName(codeFilePath) + "\\" + Path.GetFileNameWithoutExtension(codeFilePath) + Util.extension, mainWindow, editorManager); return(-1); } else { //缺少右括号 return(-2); } }