Created
January 26, 2012 07:26
-
-
Save pontusm/1681516 to your computer and use it in GitHub Desktop.
ReplaceFormat string extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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