fork download
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Net;
  5. using System;
  6.  
  7. public class Test
  8. {
  9. public static void Main()
  10. {
  11. var originalString = "My name @is ,Wan.;'; Wan";
  12. Console.WriteLine("Original string:");
  13. Console.WriteLine(originalString);
  14. Console.WriteLine();
  15.  
  16. var sanitizedString = RemoveExcept(originalString, alphas: true, spaces: true);
  17. Console.WriteLine("Sanitized string:");
  18. Console.WriteLine(sanitizedString);
  19. Console.WriteLine();
  20. }
  21.  
  22. /// <summary>
  23. /// Returns a copy of the original string containing only the set of whitelisted characters.
  24. /// </summary>
  25. /// <param name="value">The string that will be copied and scrubbed.</param>
  26. /// <param name="alphas">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
  27. /// <param name="numerics">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
  28. /// <param name="dashes">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
  29. /// <param name="underlines">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
  30. /// <param name="spaces">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
  31. /// <param name="periods">If true, all decimal characters (".") will be preserved; otherwise, they will be removed.</param>
  32. public static string RemoveExcept(string value, bool alphas = false, bool numerics = false, bool dashes = false, bool underlines = false, bool spaces = false, bool periods = false) {
  33. if (string.IsNullOrWhiteSpace(value)) return value;
  34. if (new[] { alphas, numerics, dashes, underlines, spaces, periods }.All(x => x == false)) return value;
  35.  
  36. var whitelistChars = new HashSet<char>(string.Concat(
  37. alphas ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : "",
  38. numerics ? "01234567890" : "",
  39. dashes ? "-" : "",
  40. underlines ? "_" : "",
  41. periods ? "." : "",
  42. spaces ? " " : ""
  43. ).ToCharArray());
  44.  
  45. var scrubbedValue = value.Aggregate(new StringBuilder(), (sb, @char) => {
  46. if (whitelistChars.Contains(@char)) sb.Append(@char);
  47. return sb;
  48. }).ToString();
  49.  
  50. return scrubbedValue;
  51. }
  52. }
Success #stdin #stdout 0s 131520KB
stdin
Standard input is empty
stdout
Original string:
My name @is ,Wan.;'; Wan

Sanitized string:
My name is Wan Wan