I have a string which may contains one of 4 substrings: "QUARTER:1", "QUARTER:2", "QUARTER:3", "QUARTER:4". I need to replace such substring on "MONTHS:1-3", "MONTHS:4-6", "MONTHS:7-9", "MONTHS:10-12" accordingly. How I can do this with c# Regex Replace ?
2 Answers
Pretty simple:
var result = Regex.Replace(input, @"QUARTER:([1-4])", match => {
switch (match.Groups[1].Value) {
case "1": return "MONTHS:1-3";
case "2": return "MONTHS:4-6";
case "3": return "MONTHS:7-9";
case "4": return "MONTHS:10-12";
default: return match.Value; // Can't really happen but needed for the return
}
});
Just find the correct pattern (QUARTER:([1-4])), and replace using a callback function.