删除“--”和“cr”之间的文本

本文关键字:文本 之间 删除 cr | 更新日期: 2023-09-27 18:34:24

我想删除"--"和"''cr"之间的文本。

我实际上正在读出一个文件,如果文件中有一个"--",它应该删除"--"以及所有内容,直到"''cr"。

我正在逐行阅读文件。

using (StreamReader readFile = new StreamReader(filePath))
{
    string line;
    while ((line = readFile.ReadLine()) != null)
    {
    }
}

我尝试使用子字符串来查找字符

line.Substring(line.IndexOf("--"),line.IndexOf("'cr"));

但是我在每行上查找分隔符时遇到问题

我在考虑写这样的东西

while ((line = readFile.ReadLine()) != null)
{
    if (line.Substring(line.IndexOf("--")) // If it has "--"
    {
      //Then remove all text from between the 2 delimiters
    }
}

请帮忙

谢谢

编辑:

问题

解决了,虽然我遇到了另一个问题,但我无法删除/* */之间的评论,因为评论发生在多行上。所以我需要删除/* */之间的所有文本.

有什么建议或帮助吗?谢谢

删除“--”和“cr”之间的文本

一个简单的解决方案是在行上使用正则表达式替换:

line = Regex.Replace(line, @"--.*$", "");

这假设你对'cr的意思是行的实际结尾(如果你用ReadLine()阅读它,无论如何都不包括在内),所以这会删除从--到行尾的所有内容。

要替换/* ... */注释,您可以使用:

line = Regex.Replace(line, @"--.*$|/'*.*?'*/", "");

快速电源外壳测试:

PS> $a = 'foo bar','foo bar -- some comment','foo /* another comment */ bar'
PS> $a -replace '--.*$|/'*.*?'*/'
foo bar
foo bar
foo  bar

试试这个

line.Substring(line.IndexOf("--"));

正如Joey所提到的,ReadLine()永远不会包含Environment.NewLine,''cr对应于Environment.NewLine

只是为了展示如何删除文件中每一行的注释。这是一种方式:

var newLines = from l in File.ReadAllLines(path)
               let indexComment =  l.IndexOf("--")
               select indexComment == -1 ? l : l.Substring(0, indexComment);
File.WriteAllLines(path, newLines);      // rewrite all changes to the file

编辑:如果您还想删除/**/之间的所有内容,这是一个可能的实现:

String[] oldLines = File.ReadAllLines(path);
List<String> newLines = new List<String>(oldLines.Length);
foreach (String unmodifiedLine in oldLines)
{
    String line = unmodifiedLine;
    int indexCommentStart = line.IndexOf("/*");
    int indexComment = line.IndexOf("--");
    while (indexCommentStart != -1 && (indexComment == -1 || indexComment > indexCommentStart))
    {
        int indexCommentEnd = line.IndexOf("*/", indexCommentStart);
        if (indexCommentEnd == -1)
            indexCommentEnd = line.Length - 1;
        else
            indexCommentEnd += "*/".Length;
        line = line.Remove(indexCommentStart, indexCommentEnd - indexCommentStart);
        indexCommentStart = line.IndexOf("/*");
    }
    indexComment = line.IndexOf("--");
    if (indexComment == -1)
        newLines.Add(line);
    else
        newLines.Add(line.Substring(0, indexComment));
}
File.WriteAllLines(path, newLines);

看起来您想忽略带有注释的行。怎么样

if (!line.StartsWith("--")) { /* do stuff if it's not a comment */ }

甚至

if (!line.TrimStart(' ', ''t').StartsWith("--")) { /* do stuff if it's not a comment */ }

忽略行首的空格。