Skip to content

Instantly share code, notes, and snippets.

@utilForever
Last active May 18, 2018 23:50
Show Gist options
  • Save utilForever/3b490f6c4e0dfe11f4f96390b8eca0ef to your computer and use it in GitHub Desktop.
Save utilForever/3b490f6c4e0dfe11f4f96390b8eca0ef to your computer and use it in GitHub Desktop.
Parse value range from std::string (For example, parse 10 or 10-19 only)
inline std::tuple<size_t, size_t> ParseValueRangeFromString(std::string str,
bool& isValid)
{
std::regex reValueRange("([[:digit:]]+)(-[[:digit:]]+)?");
std::smatch values;
size_t minValue = 0, maxValue = std::numeric_limits<size_t>::max();
if (!str.empty())
{
if (std::regex_match(str, values, reValueRange))
{
minValue = static_cast<size_t>(std::atoi(values[1].str().c_str()));
if (values[2].matched)
{
std::string truncatedStr = values[2].str().substr(1);
maxValue = static_cast<size_t>(std::atoi(truncatedStr.c_str()));
}
else
{
maxValue = minValue;
}
if (minValue > maxValue)
{
std::swap(minValue, maxValue);
}
}
else
{
isValid = false;
}
}
return std::make_tuple(minValue, maxValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment