I’m a bit worried about performance issue when calling RegEx.Replace to really big amount of strings since i have no idea what it does if there’s no matches.
public static void ReplaceOldWithNew(ref string input)
{
string pattern = //something here
input = Regex.Replace(input, pattern, FormatReplacement);
}
private string FormatReplacement(Match m)
{
return String.Concat("x", formatCount++);
}
should I have it like this
public static void ReplaceOldWithNew(ref string input)
{
string pattern = //something here
if (RegEx.IsMatch(input, pattern))
input = Regex.Replace(input, pattern, FormatReplacement);
}
the problem with this is that it searches the input string two times if there is match(es). Is there any solution that would search the matches only once and make new string instance only if needed. Maybe using RegEx.Matches or something.
Thanks & BR – Matti
If you inspect
Regex.Replacewith Reflector it eventually does this internally:In other words, if the pattern doesn’t match it will exit early and return the original input. Your
Regex.IsMatchusage is doing double work, but it’s the only way to know in advance whether a match exists sinceRegex.Replacereturns a string with no indication of whether a match existed to begin with. UsingMatchwith a loop orMatcheswon’t make it easy for you to reconstruct the original string since you’ll need to figure out the match indices (use theIndexproperty onMatch) and piece it all together.If you expect to use the regex alot you could look into using the
RegexOptions.Compiledoption. Declare yourRegexobject with it and reuse it throughout your code. You’ll need to do some research on that and benchmark whether it’s worth it (i.e., using that option everywhere is overkill for scenarios that don’t need it).