In regex it would be 0x[0-9a-fA-F]+
, but how to achieve it in pure c++ ?
You can use the built-in methods of std::string
to check that the first portion of the string is the literal "0x" and that the remainder of the string contains only the allowed characters. Here is the equivalent to the regular expression given in the question:
bool is_hex_notation(std::string const& s)
{
return s.compare(0, 2, "0x") == 0
&& s.size() > 2
&& s.find_first_not_of("0123456789abcdefABCDEF", 2) == std::string::npos;
}
With C++11 you can do it easily:
std::string str = "FF22ABCD16ZZ";
if (std::all_of(str.begin(), str.end(), ::isxdigit)) {
std::cout << str << " contains only hexadecimal digits" << std::endl;
}
Call strtoul
and check for an error.
Try the following
bool IsHex(const std::string& str) {
if (str.length < 3 || str[0] != '0') {
return false;
}
if (str[1] != 'x' && str[1] != 'X') {
return false;
}
for (size_t i = 2; i < str.length; i++) {
char current = str[i];
if (current >= '0' && current <= '9') {
continue;
}
if (current >= 'A' && current <= 'F') {
continue;
}
if (current >= 'a' && current <= 'f') {
continue;
}
return false;
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With