title: Using RegEx in c# to check for valid characters
body: <p>I'm having a hard time understand regex.  I have a scenario where valid characters are a-z, A-Z, 0-9 and a space.  So when I try and create a RegEx for invalid characters I have this, [^a-zA-Z0-9 ].
  Then I have strings that I want to search based on the RegEx and when it finds an invalid character, it checks if the character before it is invalid.
  for example, "test test +?test"
  So what I want to happen is if there are two invalid characters, one after the other, do nothing otherwise insert a '£'.  So the string above will be fine, no changes.  However, the string, "test test £test", should be changed to "test test ££test".</p>
  
  <p>This is my code..</p>
  
  <pre><code>public string HandleInvalidChars(string message)
      {
          const string methodName = "HandleInvalidChars";
  
          Regex specialChars = new Regex("[^a-zA-Z0-9 ]");
          string strSpecialChars = specialChars.ToString();
  
          //prev character in string which we are going to check 
          string prevChar;
  
          Match match = specialChars.Match(message); 
  
          while (match.Success) 
          {
  
              //get position of special character
              int position = match.Index;
  
              // get character before special character
              prevChar = message.Substring(position - 1, 1);
  
              //check if next character is a special character, if not insert ? escape character
              try
              {
                  if (!Regex.IsMatch(prevChar, strSpecialChars))
                  {
  
                      message = message.Insert(position, "?");
  
                  }
              }
              catch (Exception ex)
              {
                  _logger.ErrorFormat("{0}: ApplicationException: {1}", methodName, ex);
                  return message;
              }
  
  
              match = match.NextMatch();
              //loop through remainder of string until last character
  
          }
  
          return message;
      }
  </code></pre>
  
  <p>When I test it on the first string it handles the first invalid char, '+', ok but it falls over when it reaches '£'.</p>
  
  <p>Any help is really appreciated.</p>
  
  <p>Thanks :)</p>