Remove specified text from beginning of lines only if present (C#)

14,956

Solution 1

He simplest method would be to do the following for the whole block of text at once:

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

You could also split the entire text into an array of lines of text and do the following line by line with to ensure a "-- " somewhere in the middle would not be removed:

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

Solution 2

Use System.Text.RegularExpressions.Regex.Replace for a simple yet robust solution:

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

And here's a working proof in a C# Interactive session:

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

Solution 3

What about using 'TrimStart(...)'?

string line = "-- Comment";
line = line.TrimStart('-', ' ');
Share:
14,956
Zach
Author by

Zach

0xE year old C# developer, learning Python, as well as Django.

Updated on June 05, 2022

Comments

  • Zach
    Zach almost 2 years

    I have a textbox in which the user can edit text, in a scripting language. I've figured out how to let the user comment out lines in one click, but can't seem to figure out how to uncomment properly. For example, if the box has:

    Normal Text is here
    More normal text
    -- Commented text
    -- More commented text
    Normal Text again
    --Commented Text Again
    

    So, when the user selects any amount of text and decides to uncomment, the "--" is removed from the beginning of the lines that have it. The lines without the "--" should be unaffected. In short, I want an uncomment function that performs similar to the one in Visual Studio. Is there any way to accomplish this?

    Thanks