fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <regex>
  4.  
  5. void replaceSystemEnviromentTokens(std::string& var)
  6. {
  7. static std::string tokenOpening = "\\[\\[";
  8. static std::string tokenClosure = "\\]\\]";
  9. auto getEnvVal = [](const std::string& var) {
  10. char* val = getenv(var.c_str());
  11. return std::string(val ? val : "");
  12. };
  13.  
  14. std::regex re(tokenOpening + "(\\S+)" + tokenClosure);
  15. std::sregex_iterator it(var.begin(),var.end(),re);
  16. std::sregex_iterator end;
  17. while (it != end) {
  18. auto& m = *it;
  19. auto value = getEnvVal(m.str(1));
  20. if (!value.empty()) {
  21. std::regex re_replace(tokenOpening + m.str(1) + tokenClosure);
  22. var = regex_replace(var, re_replace, value);
  23. it = std::sregex_iterator(var.begin(), var.end(), re);
  24. }
  25. else {
  26. ++it;
  27. }
  28. }
  29. }
  30.  
  31. int main(int argc, char** argv)
  32. {
  33. putenv(R"(VULKAN_SDK=C:\VulkanSDK\1.2.148.1)");
  34. std::string test = "this should be converted: [[VULKAN_SDK]] this should not be converted: VULKAN_SDK]] this: [[VULKAN_SDK]]";
  35. replaceSystemEnviromentTokens(test);
  36. std::cout << test << std::endl;
  37.  
  38. test = "nothing to convert here";
  39. replaceSystemEnviromentTokens(test);
  40. std::cout << test << std::endl;
  41.  
  42. test = "something to convert here: [[PATH]]";
  43. replaceSystemEnviromentTokens(test);
  44. std::cout << test << std::endl;
  45.  
  46. test = "something [[NOT_IN_ENV]] to convert [[PATH]]. A non existing one [[MISSING]]... Stop there! Another good conversion [[PATH]].";
  47. replaceSystemEnviromentTokens(test);
  48. std::cout << test << std::endl;
  49. }
  50.  
Success #stdin #stdout 0s 4776KB
stdin
Standard input is empty
stdout
this should be converted: C:\VulkanSDK\1.2.148.1 this should not be converted: VULKAN_SDK]] this: C:\VulkanSDK\1.2.148.1
nothing to convert here
something to convert here: /usr/local/bin:/usr/bin:/bin
something [[NOT_IN_ENV]] to convert /usr/local/bin:/usr/bin:/bin. A non existing one [[MISSING]]... Stop there! Another good conversion /usr/local/bin:/usr/bin:/bin.