tags:

views:

57

answers:

3
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 ":".

+1  A: 

By using a more specific regex

new Regex(@"^[^:]*:", RegexOptions.Compiled);

Your .*: does this

  1. .* matches everything, greedily, so it runs right to the end of the string.
  2. : 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:

  1. ^ anchors the regex to the start of the string. no matches in the middle of the string can occur.
  2. [^:]* matches everything except colons, greedily, so it runs right to the first colon
  3. : can match easily, because the next character happens to be a colon. Done.

No backtracking involved, this means it is also more efficient.

Tomalak
A: 

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);
madgnome
+4  A: 

Any reason you're using regular expressions to get a simple substring?

time = time.Substring(time.IndexOf(":") + 1);
dtb
Enlightenment +1000
Bas
Sometimes the simple tool is better than the complicated one.
msarchet