If you're working with ASP.NET C# and you're looking for something that could strip out numeric or non-numeric characters from a string, you might find these helper methods useful enough.
I wrote these methods to give an additional answer to this StackOverflow question, mostly because the accepted one didn't handle null values: the behaviour of each one of them is well-documented within the <summary> text, hence there's nothing to explain here.
If you like them, feel free to leave a comment!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/// <summary> /// Strips out non-numeric characters in string, returning only digits /// ref.: https://stackoverflow.com/questions/3977497/stripping-out-non-numeric-characters-in-string /// </summary> /// <param name="input">the input string</param> /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param> /// <returns>the input string numeric part: for example, if input is "XYZ1234A5U6" it will return "123456"</returns> public static string GetNumbers(string input, bool throwExceptionIfNull = false) { return (input == null && !throwExceptionIfNull) ? input : new string(input.Where(c => char.IsDigit(c)).ToArray()); } /// <summary> /// Strips out numeric and special characters in string, returning only letters /// </summary> /// <param name="input">the input string</param> /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param> /// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZAU"</returns> public static string GetLetters(string input, bool throwExceptionIfNull = false) { return (input == null && !throwExceptionIfNull) ? input : new string(input.Where(c => char.IsLetter(c)).ToArray()); } /// <summary> /// Strips out any non-numeric/non-digit character in string, returning only letters and numbers /// </summary> /// <param name="input">the input string</param> /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param> /// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZ1234A5U6"</returns> public static string GetLettersAndNumbers(string input, bool throwExceptionIfNull = false) { return (input == null && !throwExceptionIfNull) ? input : new string(input.Where(c => char.IsLetterOrDigit(c)).ToArray()); } |