fork download
  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. public class HW
  5. {
  6. public double? H { get; private set; }
  7. public double? W { get; private set; }
  8.  
  9. public static HW FromFormula(string formula)
  10. {
  11. var decimalPattern = @"\d*(\.\d*)?";
  12. var operatorPattern = @"\s*[-+*/×÷]\s*";
  13. var r = new Regex($@"(w(?<w>{decimalPattern})|WW){operatorPattern}(h(?<h>{decimalPattern})|HH)");
  14. var m = r.Match(formula);
  15. if (!m.Success) return null; //throw new FormatException();
  16. var hw = new HW();
  17. var h = m.Groups["h"];
  18. if (h.Success) hw.H = hw.H = double.Parse(h.Value);
  19. var w = m.Groups["w"];
  20. if (w.Success) hw.W = double.Parse(w.Value);
  21. return hw;
  22. }
  23. }
  24.  
  25.  
  26. public class Test
  27. {
  28. public static void Main()
  29. {
  30. var fs = new[]
  31. {
  32. "w900×HH",
  33. "WW×h1000",
  34. "WW×HH",
  35. "w900/h100",
  36. };
  37.  
  38. foreach (var f in fs)
  39. {
  40. var hw = HW.FromFormula(f);
  41. if (hw == null)
  42. Console.WriteLine($"Invalid Formula: {f}");
  43. else
  44. Console.WriteLine($"Valid Formula: {f}, H = {hw.H}, W = {hw.W}");
  45. }
  46. }
  47. }
Success #stdin #stdout 0.03s 134592KB
stdin
Standard input is empty
stdout
Valid Formula: w900×HH, H = , W = 900
Valid Formula: WW×h1000, H = 1000, W = 
Valid Formula: WW×HH, H = , W = 
Valid Formula: w900/h100, H = 100, W = 900