仅当存在时,从行开头删除指定文本(C#)

3

我有一个文本框,用户可以在其中使用脚本语言编辑文本。我已经想出了如何让用户一键注释掉行,但似乎无法正确地取消注释。例如,如果文本框中有:

Normal Text is here
More normal text
-- Commented text
-- More commented text
Normal Text again
--Commented Text Again
所以,当用户选择任意文本并决定取消注释时,具有"--"的行的开头将被删除。没有"--"的行应该不受影响。简而言之,我想要一个类似于Visual Studio中的取消注释功能。有什么方法可以实现这个功能吗?
谢谢。

1
这似乎是一个足够简单的任务。你尝试过什么?使用正则表达式搜索"-- ",或者只需遍历行并查找以"-- "开头的行似乎是解决方案。 - Michael Petrotta
3个回答

10

使用System.Text.RegularExpressions.Regex.Replace可以得到一个简单而强大的解决方案:

Regex.Replace(str, @"^--\s*", String.Empty, RegexOptions.Multiline)

这里是一个在C#交互会话中运行的有效证明:

Microsoft (R) Visual C# Interactive Compiler version 1.2.0.60317
Copyright (C) Microsoft Corporation. All rights reserved.

Type "#help" for more information.
> using System.Text.RegularExpressions;
> var str = @"Normal Text is here
. More normal text
. -- Commented text
. -- More commented text
. Normal Text again
. --Commented Text Again";
> str = Regex.Replace(str, @"^--\s*", string.Empty, RegexOptions.Multiline);
> Console.WriteLine(str);
Normal Text is here
More normal text
Commented text
More commented text
Normal Text again
Commented Text Again

3
使用 "TrimStart(...)" 怎么样?
string line = "-- Comment";
line = line.TrimStart('-', ' ');

3
但这只会删除一个字符。 - Jim G.
这将删除任何组合的“-”和“ ”,而不仅仅是“--”。 - Daniel P

-4

最简单的方法是一次性对整个文本块执行以下操作:

string uncommentedText = yourText.Trim().Replace("-- ", "");

你也可以将整个文本拆分为文本行的数组,并逐行执行以下操作,以确保中间有"-- "不会被删除:

string uncommentedLine = yourLine.Trim().StartsWith("-- ") ?
    yourLine.Trim().Replace("-- ", "") : yourLine;

8
所提供的代码有两个缺点:
  1. 代码在字符串“yourText”中删除“ - -”出现的位置,而不仅仅是在开头。
  2. 代码不能处理破折号和文本之间没有空格的情况,例如示例的最后一行。
- artdanil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接