You could use both of the regular expressions in the question. First a match with the leading colon expression to quickly find or exclude possible lines. If that succeeds then use the full replace expression.
MatchCollection mc = Regex.Matches(Datain, ":[012345][0123456789]:[012345][0123456789].*"));
if ( mc != null && mc.Length > 0 )
{
Dataout = Regex.Replace(Datain, "[012][0123456789]:[012345][0123456789]:[012345][0123456789].*", string.Empty, RegexOptions.Compiled);
}
else
{
Dataout = Datain;
}
A variation might be
Regex finder = new Regex(":[012345][0123456789]:[012345][0123456789].*");
Regex changer = new regex("[012][0123456789]:[012345][0123456789]:[012345][0123456789].*");
if ( finder.Match(Datain).Success)
{
Dataout = changer.Replace(Datain, string.Empty);
}
else
{
Dataout = Datain;
}
Another variation would be to use the finder
as above. If the string is found then just check whether the previous two characters are digits.
Regex finder = new Regex(":[012345][0123456789]:[012345][0123456789].*");
Match m = finder.Match(Datain);
if ( m.Success && m.Index > 1)
{
if ( char.IsDigit(DataIn[m.index-1]) && char.IsDigit(DataIn[m.index-2])
{
Dataout = m.Index-2 == 0 ? string.Empty : DataIn.Substring(0, m.Index-2);
}
else
{
Dataout = Datain;
}
}
else
{
Dataout = Datain;
}
In the second and third ideas the finder
and changer
should be declared and given values before reading any lines. There is no need to execute the new Regex(...)
inside the line reading loop.