rsk*_*k82 3 c++ string pattern-matching
在正则表达式中它会是0x[0-9a-fA-F]+,但如何在纯c ++中实现它?
Rob*_*edy 13
您可以使用内置方法std::string检查字符串的第一部分是文字"0x",并且字符串的其余部分仅包含允许的字符.这相当于问题中给出的正则表达式:
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
使用 C++11 你可以轻松做到这一点:
std::string str = "FF22ABCD16ZZ";
if (std::all_of(str.begin(), str.end(), ::isxdigit)) {
std::cout << str << " contains only hexadecimal digits" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)