C#正则表达式替换

时间:2014-11-10 19:28:27

标签: c# regex

我有一个字符串,其中可能包含4个子字符串中的一个:" QUARTER:1"," QUARTER:2"," QUARTER:3",&# 34;季:4&#34 ;.我需要在" MONTHS:1-3"," MONTHS:4-6"," MONTHS:7-9","月:10-12"因此。我如何用c#Regex Replace做到这一点?

2 个答案:

答案 0 :(得分:3)

非常简单:

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
    }
});

找到正确的模式(QUARTER:([1-4])),然后使用回调函数替换。

答案 1 :(得分:1)

你不需要正则表达式。

var result = input.Replace("QUARTER:1", "MONTHS:1-3")
    .Replace("QUARTER:2", "MONTHS:4-6")
    .Replace("QUARTER:3", "MONTHS:7-9")
    .Replace("QUARTER:4", "MONTHS:10-12");