fork download
  1. using System;
  2. using System.Text;
  3. using System.Collections.Generic;
  4.  
  5. public class Test
  6. {
  7. public static string Replace(string input, ref int pos, IDictionary<string,string> vars, bool stopOnClose = false) {
  8. var res = new StringBuilder();
  9. while (pos != input.Length) {
  10. switch (input[pos]) {
  11. case '\\':
  12. pos++;
  13. if (pos != input.Length) {
  14. res.Append(input[pos++]);
  15. }
  16. break;
  17. case ')':
  18. if (stopOnClose) {
  19. return res.ToString();
  20. }
  21. res.Append(')');
  22. pos++;
  23. break;
  24. case '$':
  25. pos++;
  26. if (pos != input.Length && input[pos] == '(') {
  27. pos++;
  28. var name = Replace(input, ref pos, vars, true);
  29. string replacement;
  30. if (vars.TryGetValue(name, out replacement)) {
  31. res.Append(replacement);
  32. } else {
  33. res.Append("<UNKNOWN:");
  34. res.Append(name);
  35. res.Append(">");
  36. }
  37. pos++;
  38. } else {
  39. res.Append('$');
  40. }
  41. break;
  42. default:
  43. res.Append(input[pos++]);
  44. break;
  45. }
  46. }
  47. return res.ToString();
  48. }
  49. public static void Main() {
  50. const string input = "Here is a test string contain $(variableA) and $(variableB$(variableC))";
  51. var vars = new Dictionary<string, string> {
  52. {"variableA", "A"}, {"variableB", "B"}, {"variableC", "C"}, {"variableBC", "Y"}
  53. };
  54. int pos = 0;
  55. Console.WriteLine(Replace(input, ref pos, vars));
  56. }
  57. }
Success #stdin #stdout 0.03s 33872KB
stdin
Standard input is empty
stdout
Here is a test string contain A and Y