0

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 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need regular expressions for that.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.