comparison Core/Toolbox.cpp @ 2921:0a4428aad512

variable substitution with default value
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 07 Nov 2018 12:59:03 +0100
parents ad0e7def3338
children 0bcf46cea4e4
comparison
equal deleted inserted replaced
2920:ad0e7def3338 2921:0a4428aad512
1512 1512
1513 template<typename Out> 1513 template<typename Out>
1514 Out operator()(const boost::smatch& what, 1514 Out operator()(const boost::smatch& what,
1515 Out out) const 1515 Out out) const
1516 { 1516 {
1517 Dictionary::const_iterator found = dictionary_.find(what[1]); 1517 if (!what[1].str().empty())
1518 {
1519 // Variable without a default value
1520 Dictionary::const_iterator found = dictionary_.find(what[1]);
1518 1521
1519 if (found != dictionary_.end()) 1522 if (found != dictionary_.end())
1523 {
1524 const std::string& value = found->second;
1525 out = std::copy(value.begin(), value.end(), out);
1526 }
1527 }
1528 else
1520 { 1529 {
1521 const std::string& value = found->second; 1530 // Variable with a default value
1522 out = std::copy(value.begin(), value.end(), out); 1531 std::string key;
1532 std::string defaultValue;
1533
1534 if (!what[2].str().empty())
1535 {
1536 key = what[2].str();
1537 defaultValue = what[3].str();
1538 }
1539 else if (!what[4].str().empty())
1540 {
1541 key = what[4].str();
1542 defaultValue = what[5].str();
1543 }
1544 else if (!what[6].str().empty())
1545 {
1546 key = what[6].str();
1547 defaultValue = what[7].str();
1548 }
1549 else
1550 {
1551 throw OrthancException(ErrorCode_InternalError);
1552 }
1553
1554 Dictionary::const_iterator found = dictionary_.find(key);
1555
1556 if (found == dictionary_.end())
1557 {
1558 out = std::copy(defaultValue.begin(), defaultValue.end(), out);
1559 }
1560 else
1561 {
1562 const std::string& value = found->second;
1563 out = std::copy(value.begin(), value.end(), out);
1564 }
1523 } 1565 }
1524 1566
1525 return out; 1567 return out;
1526 } 1568 }
1527 }; 1569 };
1529 1571
1530 1572
1531 std::string Toolbox::SubstituteVariables(const std::string& source, 1573 std::string Toolbox::SubstituteVariables(const std::string& source,
1532 const std::map<std::string, std::string>& dictionary) 1574 const std::map<std::string, std::string>& dictionary)
1533 { 1575 {
1534 const boost::regex pattern("\\${(.*?)}"); 1576 const boost::regex pattern("\\${([^:]*?)}|" // ${what[1]}
1577 "\\${([^:]*?):-([^'\"]*?)}|" // ${what[2]:-what[3]}
1578 "\\${([^:]*?):-\"([^\"]*?)\"}|" // ${what[4]:-"what[5]"}
1579 "\\${([^:]*?):-'([^']*?)'}"); // ${what[6]:-'what[7]'}
1535 1580
1536 VariableFormatter formatter(dictionary); 1581 VariableFormatter formatter(dictionary);
1537 1582
1538 return boost::regex_replace(source, pattern, formatter); 1583 return boost::regex_replace(source, pattern, formatter);
1539 } 1584 }