fork download
  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. var inputTests = new[]
  9. {
  10. "5*-3",
  11. "(5--5)-3",
  12. "(5-------5)-3",
  13. "-(1-2)-3"
  14. };
  15.  
  16. foreach (var line in inputTests)
  17. {
  18. Console.WriteLine(line + " -> " + RemoveUnaryOperators(line));
  19. }
  20. }
  21.  
  22. private static Regex _regex = new Regex(@"(?<=^|[-(+*/])-(?<value>\d+|\((?:[^\(\)]|(?<open>\()|(?<-open>\)))+?(?(open)(?!))\))", RegexOptions.Compiled);
  23.  
  24. private static string RemoveUnaryOperators(string input)
  25. {
  26. var result = Regex.Replace(input ?? string.Empty, @"\s+", string.Empty);
  27. string tmp;
  28. do
  29. {
  30. tmp = result;
  31. result = _regex.Replace(result, @"(0-${value})");
  32. }
  33. while (result != tmp);
  34.  
  35. return result;
  36. }
  37. }
Success #stdin #stdout 0.04s 134720KB
stdin
Standard input is empty
stdout
5*-3  ->  5*(0-3)
(5--5)-3  ->  (5-(0-5))-3
(5-------5)-3  ->  (5-(0-(0-(0-(0-(0-(0-5)))))))-3
-(1-2)-3  ->  (0-(1-2))-3