Search code examples
c#regexvalidationuser-input

Replacing Special Characters with regex - C#


I am trying to remove special characters (with a few exceptions) from a string by using this MSDN example. I am using the NET framework v4.0 and my code is the following:

myString = Regex.Replace(myString, @"[^\w !@$*-_.]", "",
                                 RegexOptions.None);

However, during testing, I have noticed that on top of the characters listed above, it is not replacing others like [ ] \ or /. I thought these would be caught by the regular expression and it concerns me that there might be others that are not caught either.

Any advice to figure out the cause and how to solve it would be very appreciated. Thank you so much!


Solution

  • This version allows the three additional symbols you seem to be trying to add:

    Regex.Replace(
        @"a!s$d*f[a\s/df]a_s.d-f",
        @"[^\w\.!$*@-]",
        "",
        RegexOptions.None)
    

    Yields

    a!s$d*fasdfa_s.d-f
    

    The problem with your modification is that it was allowing all characters between * and _

    You could rewrite your example as:

    myString = Regex.Replace(myString, @"[^\w !@$*\-_.]", "",
                                 RegexOptions.None);
    

    Notice the escaping of the hyphen