Liger86 Liger86 - 3 months ago 12
C# Question

Removing text using regular expressions

I want to remove

"2011"
and everything before it plus a single space (
" "
) after
"2011"
.

Not quite sure how to approach this, all I could think of is a simple regex-like find and replace.

string temp;
StringBuilder sb = new StringBuilder();
string[] file = File.ReadAllLines(@"TextFile1.txt");
foreach (string line in file)
{
if (line.Contains(" "))
{
temp = line.Replace(" ", " ");
sb.Append(temp + "\r\n");
continue;
}
else
sb.Append(line + "\r\n");
}
File.WriteAllText(@"TextFile1.txt", sb.ToString());


I have modified my code and with a bit of luck got it to work. Modifications look as follows:

if (line.Contains("2011"))
{

temp = line.Substring(line.IndexOf("2011 ") + 5);


sb.Append(temp + "\r\n");

continue;

}

Answer
string s = "653 09-23-2011 21 27 32 40 52 36 ";
s = s.Substring(s.IndexOf("2011 ") + 5);

The result is that s = "21 27 32 40 52 36 "