C#/ .net字符串魔术从文本文件输入中删除注释行?

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字符串魔法的世界中是否有一些功能,它特别"理解"并有助于评论.

即使专家的答案"绝对没有",这也是一个有用的答案.

Rah*_*thi 8

你可以尝试这样:

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)

因此,您基本上可以将原始文件的内容复制到没有注释行的临时文件中.然后删除该文件并将临时文件移动到原始文件.

  • 多行注释会给这个^带来麻烦 (3认同)
  • @FᴀʀʜᴀɴAɴᴀᴍ我的意思是,这只适用于示例中显示的注释类型.问题是*令人难以置信*本地化,主要是因为对正在处理的文件的内容做了很多假设.根据在问题中提供给我们的当前信息量,这个答案在每个单词的意义上都是完整的. (2认同)
  • 不应该是`l =>!l.StartsWith("//")&&!l.StartsWith("#")`?要么是'l =>!(l.StartsWith("//")|| l.StartsWith("#"))`一行不能以`//`和`#`开头. (2认同)

suj*_*lil 5

希望这有意义:

 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)


Fat*_*tie 0

仅供参考,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    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后你就

\n\n
List<string> lines = controlFile.text.CleanLines();\nforeach (string ln in lines) Debug.Log(ln);\n
Run Code Online (Sandbox Code Playgroud)\n

  • 这与“已经”给出的其他两个答案有何不同? (6认同)