C#从字符串中删除注释 [英] C# removing comments from a string

查看:96
本文介绍了C#从字符串中删除注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WinForms NET 2.0。我正在编写一个小功能来修剪某些选定文本的注释。这样做是将选定的文本分隔成几行,然后:

I'm using WinForms NET 2.0. I am coding a small function to trim comments from some selected text. What it does is split the selected text by separate lines, and then:


  • 如果该行不包含任何注释,则将其追加。 li>
  • 如果该行包含一些文本,并在其后加上注释,则该行将附加有修剪后的注释。

  • 如果该行以注释开头,则不会被附加。这是在if语句中。

  • 如果该行为空,则不会附加该行。这也位于if语句中。

这是我的代码:

        string[] lines = tb.SelectedText.Split('\n');
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < lines.Length; i++)
        {
            if ((lines[i].Trim() != string.Empty) || !Regex.IsMatch(lines[i], @"^\s*;(.*)$"))
            {
                if (Regex.IsMatch(lines[i], @"^(.*);(.*)$"))
                    sb.AppendLine(lines[i].Substring(0, lines[i].IndexOf(';')).Trim());
                else
                    sb.AppendLine(lines[i]);
            }
        }
        tb.SelectedText = sb.ToString();

问题是,它没有按预期工作。假设我有以下文本:

The problem is, it isn't working as intended. Suppose if I have the following text:

test    ;test

test2   ;test

我希望这会修剪注释并删除空白行,但是不行,空白行仍然存在。为什么是这样?我检查了行是否为空,因此StringBuilder不应在行为空白的情况下追加行,但出于某些原因。

I would expect this to trim the comments and remove the blank line, but no, the blank line is STILL there. Why is this? I checked if the line was empty, so the StringBuilder shouldn't append the line if it's blank, but for some reason it does.

另外,出于某些原因,stringbuilder追加一行。

Also, for some reason the stringbuilder appends an extra line. How to get rid of that?

推荐答案

替换||在&&&并使用 \r\n代替 \n。试试这个:

Replace the || in the if-statement by && and use "\r\n" instead of "\n". Try this:

var lines = textBox2.SelectedText.Split(new [] {"\r\n"}, StringSplitOptions.None);
var sb = new StringBuilder();

for (int i = 0; i < lines.Length; i++)
{
    var line = lines[i].Trim();
    if ((line != string.Empty) && !Regex.IsMatch(line, @"^\s*;(.*)$"))
    {
        if (Regex.IsMatch(line, @"^(.*);(.*)$"))
            sb.AppendLine(line.Substring(0, line.IndexOf(';')).Trim());
        else
            sb.AppendLine(line);
    }
}
textBox2.SelectedText = sb.ToString();

或者使用LinQ和?:表达式:

Or with LinQ and "?:" expression:

var lines = textBox2.SelectedText .Split(new [] {"\r\n"}, StringSplitOptions.None);
var sb = new StringBuilder();

foreach (var line in lines.Select(t => t.Trim())
                          .Where(line => (line != string.Empty) && !Regex.IsMatch(line, @"^\s*;(.*)$")))
{
    sb.AppendLine(Regex.IsMatch(line, @"^(.*);(.*)$") ? line.Substring(0, line.IndexOf(';')).Trim() : line);
}
textBox2.SelectedText = sb.ToString();

这篇关于C#从字符串中删除注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆