I'm looking to strip out non-numeric characters in a string in ASP.NET C#, i.e. 40,595 p.a. would end up as 40595.
Thanks
I'm looking to strip out non-numeric characters in a string in ASP.NET C#, i.e. 40,595 p.a. would end up as 40595.
Thanks
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");
Strips out all non Numeric characters
Public Function OnlyNumeric(strIn As String) As String
Try
Return Regex.Replace(strIn, "[^0-9]", "")
Catch
Return String.Empty
End Try
End Function
If you're working in VB and ended up here, the ".Where" threw an error for me. Got this from here: https://forums.asp.net/t/1067058.aspx?Trimming+a+string+to+remove+special+non+numeric+characters
Function ParseDigits(ByVal inputString as String) As String
Dim numberString As String = ""
If inputString = Nothing Then Return numberString
For Each c As Char In inputString.ToCharArray()
If c.IsDigit Then
numberString &= c
End If
Next c
Return numberString
End Function
As of C# 3.0, you should use method groups in lieu of lambda expressions where possible. This is because using method groups results in one less redirect, and is thus more efficient.
The currently accepted answer would thus become:
private static string GetNumbers(string input)
{
return new string(input.Where(char.IsDigit).ToArray());
}