Reputation: 1252
string time = "Job started: donderdag 6 mei 2010 at 20:00:02"
var filterReg = new Regex(@".*:", RegexOptions.Compiled);
time = filterReg.Replace(time, String.Empty);
Is it possible to stop after the first occurence? so at the first ":".
Upvotes: 0
Views: 1456
Reputation: 338158
By using a more specific regex
new Regex(@"^[^:]*:", RegexOptions.Compiled);
Your .*:
does this
.*
matches everything, greedily, so it runs right to the end of the string.:
tries to match, so the regex engine goes back one character at a time (this is called backtracking) to find a match. It stops at the first colon it finds (seen from the end of the string)whereas ^[^:]*:
does this:
^
anchors the regex to the start of the string. no matches in the middle of the string can occur.[^:]*
matches everything except colons, greedily, so it runs right to the first colon:
can match easily, because the next character happens to be a colon. Done.No backtracking involved, this means it is also more efficient.
Upvotes: 2
Reputation: 217263
Any reason you're using regular expressions to get a simple substring?
time = time.Substring(time.IndexOf(":") + 1);
Upvotes: 3
Reputation: 49970
Use this regex .*?:
with the Replace
overload :
string time = "Job started: donderdag 6 mei 2010 at 20:00:02"
var filterReg = new Regex(@".*?:", RegexOptions.Compiled);
filterReg.Replace(time, String.Empty, 1);
Upvotes: 0