I. 写一个正则表达式,要求判断一个数是否满足以下条件:
>= val1 && < val2 ...
1. val1和va2要求支持浮点数;void ParseSpec(const std::string& spec) { m_validSpec = false; m_Ops.clear(); std::string specStr = boost::trim_copy(spec); if (specStr.empty()) { m_validSpec = true; return; } // we added "AND" as prefix for consistent handling later specStr = "AND " + specStr; boost::regex reg(specExp); m_validSpec = boost::regex_match(specStr, reg); if (!m_validSpec) return; reg.set_expression(logicalExp+relationExp); boost::smatch what; std::string::const_iterator start = specStr.begin(), end = specStr.end(); while (boost::regex_search(start, end, what, reg)) { std::string opStr = std::string(what[1].first, what[1].second); std::transform(opStr.begin(), opStr.end(), opStr.begin(), boost::bind(&std::toupper, _1)); m_Ops.push_back(std::make_pair(opStr, std::make_pair(std::string(what[2].first, what[2].second), atof(std::string(what[3].first, what[3].second).c_str())))); start = what[0].second; } }
bool IsValueOK(double valueToCheck) const { if (!m_validSpec) return true; /* Below logic will follow logic in C language For example: A && B || C If A (true), run B, but skipping run C, otherwise, run C, but skipping run B */ bool ret = true; for (BOOST_AUTO(it, m_Ops.begin()); it != m_Ops.end(); ++it) { if (it->first == "AND" || it->first == "&&") { if (!ret) continue; // skip this op, like C ret = ret && ::RelationOp(valueToCheck, it->second.second, it->second.first); } if (it->first == "OR" || it->first == "||") { if (ret) continue; // skip this op, like C ret = ret || ::RelationOp(valueToCheck, it->second.second, it->second.first); } } return ret; }
以上代码模仿逻辑运算AND/OR,满足短路原则:遇到AND,前面计算结果为FALSE,跳过此次运算;遇到OR,前面计算结果为TRUE,跳过此次运算。