0

I want to extract a number from a string in C#. The input string is a single line, but otherwise can be anything. I want to extract with the following rules:

  • The first character can be a minus sign, but doesn't have to be
  • There can be 0 or 1 periods/decimal-points
  • All other characters are numeric

By way of example, from the first string I want to return the second one:

"-12b9" -> "-129",
"foobar" -> "",
"12..34" -> "12.34",
"-1-2-3" -> "-123",
"foo1bar-2" -> "12"

This code works, but I'm sure there must be a way to avoid the gore:

text = Regex.Replace(text, @"[^0-9\-\.]", @"", RegexOptions.ECMAScript);
text = text.Substring(0, 1) + Regex.Replace(text.Substring(1), @"[^0-9\.]", @"", RegexOptions.ECMAScript);
if (text.IndexOf('.') > 0)
{
    text = text.Substring(0, text.IndexOf('.') + 1) + Regex.Replace(text.Substring(text.IndexOf('.') + 1), @"[^0-9\-]", @"", RegexOptions.ECMAScript);
}

0 Answers0