title: How to perform multiple Regex replacements in sequence from a list of unique items cleanly in C#
body: <p>I'm trying to find a cleaner way of performing multiple sequential replacements on a single string where each replacement has a unique pattern and string replacement.</p>
  
  <p>For example, if I have 3 pairs of patterns-substitutions strings:</p>
  
  <p><code>1. /(?&lt;!\\)\\n/, "\n"</code></p>
  
  <p><code>2. /(\\)(?=[\;\:\,])/, ""</code></p>
  
  <p><code>3. /(\\{2})/, "\\"</code></p>
  
  <p>I want to apply regex replacement 1 on the original string, then apply 2 on the output of 1, and so on and so forth.</p>
  
  <p>The following console program example does exactly what I want, but it has a lot of repetition, I am looking for a cleaner way to do the same thing.</p>
  
  <p><strong>SanitizeString</strong>
  </p>
  
  <pre><code>static public string SanitizeString(string param)
  {
      string retval = param;
      //first replacement
      Regex SanitizePattern = new Regex(@"([\\\;\:\,])");
      retval = SanitizePattern.Replace(retval, @"\$1");
  
      //second replacement
      SanitizePattern = new Regex(@"\r\n?|\n");
      retval = SanitizePattern.Replace(retval, @"\n");
  
      return retval;
  }
  </code></pre>
  
  <p><strong>ParseCommands</strong></p>
  
  <pre><code>static public string ParseCommands(string param)
  {
      string retval = param;
      //first replacement
      Regex SanitizePattern = new Regex(@"(?&lt;!\\)\\n");
      retval = SanitizePattern.Replace(retval, System.Environment.NewLine);
  
      //second replacement
      SanitizePattern = new Regex(@"(\\)(?=[\;\:\,])");
      retval = SanitizePattern.Replace(retval, "");
  
      //third replacement
      SanitizePattern = new Regex(@"(\\{2})");
      retval = SanitizePattern.Replace(retval, @"\");
  
      return retval;
  }
  </code></pre>
  
  <p><strong>Main</strong></p>
  
  <pre><code>using System;
  using System.IO;
  using System.Text.RegularExpressions;
  
  ...
  
  static void Main(string[] args)
  {
      //read text that contains user input
      string sampleText = File.ReadAllText(@"c:\sample.txt");
  
      //sanitize input with certain rules
      sampleText = SanitizeString(sampleText);
      File.WriteAllText(@"c:\sanitized.txt", sampleText);
  
      //parses escaped characters back into the original text
      sampleText = ParseCommands(sampleText);
      File.WriteAllText(@"c:\parsed_back.txt", sampleText);
  }
  </code></pre>
  
  <p>Don't mind the file operations. I just used that as a quick way to visualize the actual output. In my program I'm going to use something different.</p>