Paulo Rocha
Paulo Rocha

Reputation: 87

Remove lines that contain number between two underscores

I would like to remove the lines of a richtextbox that contains a number between two underscores.

On the richtextbox, I have the following values (examples):

Z_OBJECTS
Z_1_OBJECTS
Z_DEBUG
Z_1_DEBUG
Z_2_DEBUG
Z_TI_PROJECTS
Z_1_TI_PROJECTS

I want to keep only the lines Z_OBJECT, Z_TI_PROJECTS and Z_DEBUG, removing the lines that contains 1_, etc.

I'm using this function here, which works fine, but I think Regex would be better:

int total = 22;
for (int i = 1; i <= total; i++)
{
    List<string> finalLines = richTextBox1.Lines.ToList();
    finalLines.RemoveAll(x => x.StartsWith("Z_" + i + "_"));
    richTextBox1.Lines = finalLines.ToArray();
}

What I got in Regex is this:

richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^Z_\d*_", "", RegexOptions.Multiline);

Which will not remove the rest of the line.

Appreciate any help.

Upvotes: 0

Views: 207

Answers (1)

Jerry
Jerry

Reputation: 71578

Simply extend the match for the rest of the line:

@"^Z_\d+_.*$"

And I think it's better if you use \d+ (or [0-9]+), since you're explicitly looking for numbers between underscores.

Upvotes: 2

Related Questions