views:

119

answers:

4

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

A: 

Have a look at

string.StartsWith()

Specifically,

string.StartsWith("--")

The rest should be easy to figure out.

Charlie Salts
+1  A: 

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

string line = "-- Comment";
line = line.TrimStart('-', ' ');
artdanil
+1  A: 

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;
Kelsey
+1 for removing spaces at start
PostMan
The presented code has 2 drawbacks:1. code removes occurances of "-- " everywhere in the string `yourText`, and not only in the beginning;2. code does not handle situation when there is no space in between dashes and text, as in the last line of sample.
artdanil
A: 

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 an interactive IronPython session:

IronPython 2.6.1 (2.6.10920.0) on .NET 4.0.30319.1
Type "help", "copyright", "credits" or "license" for more information.
>>> from System.Text.RegularExpressions import Regex, RegexOptions
>>> str = """Normal Text is here
... More normal text
... -- Commented text
... -- More commented text
... Normal Text again
... --Commented Text Again
... """
>>> print Regex.Replace(str, '^--\s*', '', RegexOptions.Multiline)
Normal Text is here
More normal text
Commented text
More commented text
Normal Text again
Commented Text Again
Atif Aziz