[C#] 3 best ways to remove all special characters from string

No comments
You want to remove characters \ /:*?"<>|!@#$%^&() from a string?
Very easy! Follow some method:

1. Remove all special characters
string rExp = "[^\w\d]";
string tmp = Regex.Replace(n, rExp, "");

2. Remove all special characters but allow some
Example: Allow . and _
Regex.Replace(input, "[^a-zA-Z0-9._]", string.Empty)

3. Easy function remove all special characters, but allow "_"

 public static string Remove_Special_Characters(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

No comments :

Post a Comment