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::smatch m;
  16. while (std::regex_search(var, m, re)) {
  17. auto value = getEnvVal(m.str(1));
  18. if (!value.empty()) {
  19. std::regex re(tokenOpening + m.str(1) + tokenClosure);
  20. var = regex_replace(var, re, value);
  21. }
  22. }
  23. }
  24.  
  25. int main(int argc, char** argv)
  26. {
  27. putenv(R"(VULKAN_SDK=C:\VulkanSDK\1.2.148.1)");
  28. std::string test = "this should be converted: [[VULKAN_SDK]] this should not be converted: VULKAN_SDK]] this: [[VULKAN_SDK]]";
  29. replaceSystemEnviromentTokens(test);
  30. std::cout << test << std::endl;
  31.  
  32. test = "nothing to convert here";
  33. replaceSystemEnviromentTokens(test);
  34. std::cout << test << std::endl;
  35.  
  36. test = "something to convert here: [[PATH]]";
  37. replaceSystemEnviromentTokens(test);
  38. std::cout << test << std::endl;
  39. }
Success #stdin #stdout 0s 4996KB
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