Hey Im looking to strip out non-numeric characters in a string in ASP.NET C#
So i.e 40,595 p.a.
would end up with 40595
Thanks
The accepted answer is great, however it doesn't take NULL values into account, thus making it unusable in most scenarios.
This drove me into using these helper methods instead. The first one answers the OP, while the others may be useful for those who want to perform the opposite:
///
/// Strips out non-numeric characters in string, returning only digits
/// ref.: https://stackoverflow.com/questions/3977497/stripping-out-non-numeric-characters-in-string
///
/// the input string
/// if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.
/// the input string numeric part: for example, if input is "XYZ1234A5U6" it will return "123456"
public static string GetNumbers(string input, bool throwExceptionIfNull = false)
{
return (input == null && !throwExceptionIfNull)
? input
: new string(input.Where(c => char.IsDigit(c)).ToArray());
}
///
/// Strips out numeric and special characters in string, returning only letters
///
/// the input string
/// if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.
/// the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZAU"
public static string GetLetters(string input, bool throwExceptionIfNull = false)
{
return (input == null && !throwExceptionIfNull)
? input
: new string(input.Where(c => char.IsLetter(c)).ToArray());
}
///
/// Strips out any non-numeric/non-digit character in string, returning only letters and numbers
///
/// the input string
/// if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.
/// the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZ1234A5U6"
public static string GetLettersAndNumbers(string input, bool throwExceptionIfNull = false)
{
return (input == null && !throwExceptionIfNull)
? input
: new string(input.Where(c => char.IsLetterOrDigit(c)).ToArray());
}
For additional info, read this post on my blog.