Bas
Bas

Reputation: 1252

How to let regex know that it should stop after a first occurence?

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

Answers (3)

Tomalak
Tomalak

Reputation: 338158

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.

Upvotes: 2

dtb
dtb

Reputation: 217263

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

time = time.Substring(time.IndexOf(":") + 1);

Upvotes: 3

Julien Hoarau
Julien Hoarau

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

Related Questions