Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
String str = "a12334tyz78x"; str = str. replaceAll("[^\\d]", ""); You can try this java code in a function by taking the input value and returning the replaced value as per your requirement.
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());
}
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]
.
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());
}
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With