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

I have a text box in which a user can edit text in a scripting language. I figured out how to allow the user to comment out lines with one click, but cannot figure out how to properly uncomment. For example, if the field contains:

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 he has. Lines without a “-” should not be affected. In short, I need an uncomment function that works similarly to a function in Visual Studio. Is there any way to do this?

thanks

+3
source share
3 answers

:

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

, "-- " - :

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

System.Text.RegularExpressions.Regex.Replace , :

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

#:

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
+10

How to use 'TrimStart (...)'?

string line = "-- Comment";
line = line.TrimStart('-', ' ');
+3
source

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


All Articles