Hello ohmmega,
i need this about 200 times in a time critical application, so i just
want to have the best option.
i've not measured the time yet, but that's a good point - i will try
this next.
thanks so far
rené
If you still want to go the regex way, you basically have two options:
See if you can find a match for this:
^[^@]*(@[^@]*){5}$
Or do a Regex.Replace and replace everything that't not a @ with nothing
and measure the length of the text afterwards:
Regex.Replace(inputstring, "[^@]", "").Length > 5
When using a regular expression, make sure you're usign a static instance
with the option RegexOption.Compiled set for performance reasons.
Like this
private static Regex rx = new Regex(pattern, RegexOptions.Compiled);
then reference this instance when using the expression.
Also add a static constructor to the class which calls rx.Match("");, that
way your performance needy code will not suffer the recompilation of the
regex.
You can also use a tool like The Regulator to generate an Assembly with the
compiled regex in there. This would give you the performance boost of not
having the regex compiled from the executable at all.
Even though this is a nice excercise in Regular expressions, I think that
simple string manupulations would be much faster...
public bool HasFiveAts(string input)
{
int count = 0;
foreach(char c in inputstring)
{
if (c == '@') { count++; }
// might even test for if (count > 5) {return false;}, but you'd have
to test that for performance
}
return count == 5
}