Skip to content

Instantly share code, notes, and snippets.

@pontusm
Created January 26, 2012 07:26
Show Gist options
  • Save pontusm/1681516 to your computer and use it in GitHub Desktop.
Save pontusm/1681516 to your computer and use it in GitHub Desktop.
ReplaceFormat string extension
/// <summary>
/// This class is used for replacing parts of a string with other content.
/// </summary>
public static class StringExtensions
{
public static string ReplaceFormat(this string str, string format, string replacement)
{
return ReplaceFormat(str, format, match => replacement);
}
public static string ReplaceFormat(this string str, string format, MatchEvaluator evaluator)
{
int pos = format.IndexOf("{0}");
if (pos < 0)
throw new ArgumentException("Format argument must contain '{0}'.");
var prefix = format.Substring(0, pos);
var suffix = format.Substring(pos + 3);
var pattern = BuildExpression(prefix, suffix);
return Regex.Replace(str, pattern, evaluator);
}
private static string BuildExpression(string prefix, string suffix)
{
return string.Format("(?<={0})(.*?)(?={1})", Regex.Escape(prefix), Regex.Escape(suffix));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment