I have a function checks if an expression matches a regex, and returns a boost::regex_constants::error_type, it logs the error in case of exception:
boost::regex_constants::error_type RegexMatch(const std::string& p_expression, const std::string& p_pattern)
{
boost::regex_constants::error_type returnValue = boost::regex_constants::error_unknown;
try
{
if (boost::regex_match(p_expression, boost::regex(p_pattern)))
{
returnValue = boost::regex_constants::error_ok;
}
else
{
returnValue = boost::regex_constants::error_no_match;
}
}
catch(boost::regex_error& e)
{
returnValue = e.code();
LOG_ERROR("Error checking if [%s] expression matches pattern [%s]: boost::regex_error [%s]",
p_expression.c_str(),
p_pattern.c_str(),
e.what());
}
return returnValue;
}
But in client side, caller gets only boost::regex_constants::error_type
as result, while, depending on the context, client may want to display a "human readable" error.
Now my question is to know if there is a native boost function to do that ? Because I couldn't find one, I then have done my own function:
std::string BoostRegexErrorTypeToString(const boost::regex_constants::error_type p_boostRegexErrorType)
{
return boost::regex_error(p_boostRegexErrorType).what();
}
Note that I return a std::string
instead of directly a const char*
(return by what()
) because when returning a const char*
, for some error types, for example error_ok
, "et*)" is returned instead of "Success".
And finally, to test this code you can use following loop:
for (int intErrorType = boost::regex_constants::error_ok; // error_ok is the first
intErrorType <= boost::regex_constants::error_unknown; // error_unknown is the last
++intErrorType)
{
const boost::regex_constants::error_type errorType = (boost::regex_constants::error_type)intErrorType;
LOG_DEBUG("Regex error [%d] text is [%s]",
errorType,
BoostRegexErrorTypeToString(errorType).c_str());
}
Thanks