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:
- If the line contains no comments, it is appended.
- If the line contains some text followed by comments, it is appended with comments trimmed.
- If the line starts with a comment, it does not get appended. This is in the if statement.
- If the line is blank, it does not get appended. This is also in the if statement.
Here is my code:
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
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.
Also, for some reason the stringbuilder appends an extra line. How to get rid of that?
Replace the || in the if-statement by && and use “\r\n” instead of “\n”. Try this:
Or with LinQ and “?:” expression: