Search code examples
c#.netregexregexp-replace

How to conditionally match and replace words in a statement using regex in C#


I wonder if there's anyway to make "switch" replaces in RegEx.

For example, string:

round square unknown liquid

And pattern is: \w+

And imaginary replacement something like:

if (round) then "Ball" else if (square) then "Box" else if (liquid) then "Water" else if (hot) then "Fire"

And result would be

Ball Box unknown Water

The idea is to use only patterns and replacements, without any C# code.

Details or clarity:

var Text = "round square unknown liquid";
    
var Pattern = @"\w+";
var Replacement = @"if (round) then Ball else if (square) then Box else if (liquid) then Water else if (hot) then Fire"; // <-- is this somehow possible?

var Result = new Regex(Pattern).Replace(Text, Replacement);

Console.WriteLine(Result);

Expected output:

Ball Box unknown Water


Solution

  • This is indeed not possible and it should not bother you that it is not possible.

    Is it possible to build a submarine just from paper? No. Just need to add a few ingredients.

    But were it not for the "only pure regex" constraint, this is what I would have done:

    var dictionaryReplace = new Dictionary<string, string>
    {
        {"round","Ball"},
        {"square","Box"},
        {"liquid","Water"},
        {"hot","Fire"}, 
    };
    
    var Text = "round square unknown liquid";
    
    var Pattern = $"({string.Join("|", dictionaryReplace.Keys)})"; //(round|square|liquid|hot)
    var Result = new Regex(Pattern).Replace(Text, x => dictionaryReplace[x.Value]);
    
    Console.WriteLine(Result); //Ball Box unknown Water