C # /. NET string magic to remove comment lines from text file input?

Let's say you have a text file that you read as a long line:

123 123 123 123 123 123 // Just a comment 123 123 123 123 123 123 # Just a comment 123 123 123 

Usually you break it into lines like this (example in Unity3D),

  List<string> lines = new List<string>( controlFile.text.Split(new string[] { "\r","\n" }, StringSplitOptions.RemoveEmptyEntries)); 

.NET offers an incredible amount of string magic, such as formatting and more.

I wonder if there is magic available to easily delete comments?

NOTE. Of course, this can be done using regex, etc. As SonerGönül points out, you can usefully make it with .Where and .StartsWith

My question is: is there any tool in the .NET universe string magic , which specifically “understands” and helps with comments .

Even if the expert’s answer is “definitely not,” that’s a useful answer.

+5
source share
3 answers

SonyGönül's FYI Rahul answer is incorrect , the code has an error and does not work.

To keep everyone typing, here is a functioning / tested answer that just uses matching.

In connection with the issue under discussion, it seems that not everything that is SPECIALLY built into .Net, which "understands" typical comments in the text. You just need to write this from scratch using a mapping similar to this ...

 // ExtensionsSystem.cs, your handy system-like extensions using UnityEngine; using System.Collections.Generic; using System; using System.Text.RegularExpressions; using System.Linq; public static class ExtensionsSystem { public static List<string> CleanLines(this string stringFromFile) { List<string> result = new List<string>( stringFromFile .Split(new string[] { "\r","\n" }, StringSplitOptions.RemoveEmptyEntries) ); result = result .Where(line => !(line.StartsWith("//") || line.StartsWith("#"))) .ToList(); return result; } } 

and then you

 List<string> lines = controlFile.text.CleanLines(); foreach (string ln in lines) Debug.Log(ln); 
0
source

You can try the following:

 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); 

This way you can basically copy the contents of the source file into a temporary file that does not have a comment line. Then delete the file and move the temp file to the source file.

+8
source

Hope this makes sense:

  string[] comments = { "//", "'", "#" }; var CommentFreeText = File.ReadLines("fileName Here") .Where(X => !comments.Any(Y => X.StartsWith(Y))); 

You can populate comments[] with the comment characters you want to remove from textFile. When reading text, all lines starting with any of the comment characters are deleted.

And you can write it back using:

 File.WriteAllLines("path", CommentFreeText); 
+5
source

Source: https://habr.com/ru/post/1241137/


All Articles