Reputation: 6541
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
.
Upvotes: 187
Views: 160815
Reputation: 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
Upvotes: 0
Reputation: 79
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());
}
Upvotes: 3
Reputation: 19486
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
Upvotes: 0
Reputation: 163
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");
Upvotes: 10
Reputation: 9564
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:
/// <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());
}
For additional info, read this post on my blog.
Upvotes: 0
Reputation: 6024
Another option ...
private static string RemoveNonNumberDigitsAndCharacters(string text)
{
var numericChars = "0123456789,.".ToCharArray();
return new String(text.Where(c => numericChars.Any(n => n == c)).ToArray());
}
Upvotes: 7
Reputation: 219
An extension method will be a better approach:
public static string GetNumbers(this string text)
{
text = text ?? string.Empty;
return new string(text.Where(p => char.IsDigit(p)).ToArray());
}
Upvotes: 10
Reputation: 158389
There are many ways, but this should do (don't know how it performs with really large strings though):
private static string GetNumbers(string input)
{
return new string(input.Where(c => char.IsDigit(c)).ToArray());
}
Upvotes: 357
Reputation: 31458
Feels like a good fit for a regular expression.
var s = "40,595 p.a.";
var stripped = Regex.Replace(s, "[^0-9]", "");
"[^0-9]"
can be replaced by @"\D"
but I like the readability of [^0-9]
.
Upvotes: 95
Reputation: 2098
Here is the code using Regular Expressions:
string str = "40,595 p.a.";
StringBuilder convert = new StringBuilder();
string pattern = @"\d+";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(str);
foreach (Match match in matches)
{
convert.Append(match.Groups[0].ToString());
}
int value = Convert.ToInt32(convert.ToString());
Upvotes: 0
Reputation: 5421
Well, you know what the digits are: 0123456789, right? Traverse your string character-by-character; if the character is a digit tack it onto the end of a temp string, otherwise ignore. There may be other helper methods available for C# strings but this is a generic approach that works everywhere.
Upvotes: 0
Reputation: 4007
Use either a regular expression that's only capturing 0-9 and throws away the rest. A regular expression is an operation that's going to cost a lot the first time though. Or do something like this:
var sb = new StringBuilder();
var goodChars = "0123456789".ToCharArray();
var input = "40,595";
foreach(var c in input)
{
if(goodChars.IndexOf(c) >= 0)
sb.Append(c);
}
var output = sb.ToString();
Something like that I think, I haven't compiled though..
LINQ is, as Fredrik said, also an option
Upvotes: 6