Fat*_*tie 5 .net c# linq string
假设您将文本文件作为长字符串读入:
123 123 123
123 123 123
// Just a comment
123 123 123
123 123 123
# Just a comment
123 123 123
Run Code Online (Sandbox Code Playgroud)
您通常将其拆分为类似这样的行(Unity3D中的示例),
List<string> lines = new List<string>(
controlFile.text.Split(new string[] { "\r","\n" },
StringSplitOptions.RemoveEmptyEntries));
Run Code Online (Sandbox Code Playgroud)
.NET提供了大量的字符串魔法,例如格式化等等.
我想知道,是否有一些可用的魔术可以轻松删除评论?
注意 - 当然,人们可以使用正则表达式等来做到这一点.正如SonerGönül指出的那样,可以使用.Where和.StartsWith
我的问题是,在.NET字符串魔法的世界中是否有一些功能,它特别"理解"并有助于评论.
即使专家的答案"绝对没有",这也是一个有用的答案.
你可以尝试这样:
var t= Path.GetTempFileName();
var l= File.ReadLines(fileName).Where(l => !l.StartsWith("//") || !l.StartsWith("#"));
File.WriteAllLines(t, l);
File.Delete(fileName);
File.Move(t, fileName);
Run Code Online (Sandbox Code Playgroud)
因此,您基本上可以将原始文件的内容复制到没有注释行的临时文件中.然后删除该文件并将临时文件移动到原始文件.
希望这有意义:
string[] comments = { "//", "'", "#" };
var CommentFreeText = File.ReadLines("fileName Here")
.Where(X => !comments.Any(Y => X.StartsWith(Y)));
Run Code Online (Sandbox Code Playgroud)
您可以comments[]使用要从textFile中删除的注释符号填充它.在阅读文本时,它将消除以任何注释符号开头的所有行.
您可以使用以下方法将其写回:
File.WriteAllLines("path", CommentFreeText);
Run Code Online (Sandbox Code Playgroud)
仅供参考,Rahul 基于 SonerG\xc3\xb6n\xc3\xbcl 的答案是错误的,代码有错误并且不起作用。
\n\n为了节省任何人的打字时间,这里有一个仅使用匹配的功能/测试答案。
\n\n关于当前的问题,似乎.Net 中没有专门内置任何内容来“理解”文本中的典型注释。你只需要使用这样的匹配从头开始编写它......
\n\n// ExtensionsSystem.cs, your handy system-like extensions\nusing UnityEngine;\nusing System.Collections.Generic;\nusing System;\nusing System.Text.RegularExpressions;\nusing System.Linq;\n\npublic static class ExtensionsSystem\n {\n public static List<string> CleanLines(this string stringFromFile)\n {\n List<string> result = new List<string>(\n stringFromFile\n .Split(new string[] { "\\r","\\n" },\n StringSplitOptions.RemoveEmptyEntries)\n );\n\n result = result\n .Where(line => !(line.StartsWith("//")\n || line.StartsWith("#")))\n .ToList();\n\n return result;\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n\n然后你就
\n\nList<string> lines = controlFile.text.CleanLines();\nforeach (string ln in lines) Debug.Log(ln);\nRun Code Online (Sandbox Code Playgroud)\n