fork(11) download
  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. public class Test
  5. {
  6. public static Decimal ExtractDecimalFromString(string str)
  7. {
  8.  
  9. Regex digits = new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*");
  10. Match mx = digits.Match(str);
  11. //Console.WriteLine("Input {0} - Digits {1} {2}", str, mx.Success, mx.Groups);
  12.  
  13. return mx.Success ? Convert.ToDecimal(mx.Groups[1].Value) : 0;
  14. }
  15.  
  16. public static void ProcessString(string str) {
  17. Console.WriteLine("{0} -> {1}", str, ExtractDecimalFromString(str));
  18. }
  19. public static void Main()
  20. {
  21. Console.WriteLine("Conversions");
  22. ProcessString("12345");
  23. ProcessString("12345.678");
  24. ProcessString("I have $.678 to my name");
  25. ProcessString("I have $-.678 to my name");
  26. ProcessString("-12345.678");
  27. ProcessString("-12345.678 987");
  28. ProcessString(" b987z ");
  29. ProcessString("Bill: -12345.678 OK");
  30. ProcessString("Hello World");
  31. }
  32. }
Success #stdin #stdout 0.09s 24464KB
stdin
Standard input is empty
stdout
Conversions
12345 -> 12345
12345.678 -> 12345.678
I have $.678 to my name -> 0.678
I have $-.678 to my name -> -0.678
-12345.678 -> -12345.678
-12345.678 987 -> -12345.678
  b987z   -> 987
Bill: -12345.678 OK -> -12345.678
Hello World -> 0