我希望能够循环遍历正在根据正则表达式进行测试的字符串,以及它是否无法输出失败的字符串其余部分。
即
boost::regex const string_matcher("[0-9]{5}");
if (boost::regex_match(12A45,string_matcher))
{
DCS_LOG_DEBUG("Correct\n");
}
else
{
DCS_LOG_DEBUG("Incorrect\n");
}
所以输出是
"A45"
最佳答案
你会使用类似的东西:
(^[0-9]{5}$)|^(?:[0-9]{0,5})(.*)$
有两个捕获组和一个非捕获组((?:...)
中的一个)
第一个是“正确”的数据。该字符串由 5 位数字组成。否则,将跳过 0-5 位数字,并将第一个“错误”字符放入第二个捕获 (.?)
中。请注意,即使字符串为空,此捕获也会成功。
小样本:
std::regex const string_matcher("(^[0-9]{5}$)|^(?:[0-9]{0,5})(.*)$");
std::match_results<std::string::const_iterator> match;
std::string str("123456");
std::cout << "Success: " << std::boolalpha << std::regex_match(str, match, string_matcher) << std::endl;
std::cout << "Num of sub-matches: " << match.size() << std::endl;
std::cout << "Success capture: " << std::boolalpha << match[1].matched << " at " << match.position(1) << ": '" << match[1].str() << "'" << std::endl;
std::cout << "First failed character: " << std::boolalpha << match[2].matched << " at " << match.position(2) << ": '" << match[2].str() << "'" << std::endl;
(遗憾的是我无法在 ideone 上编译它,因为它不支持正则表达式,在 VC++ 上测试)
测试它:
(empty string)
1
AA
1AA
12345
123456
12345AA
关于c++ - 循环字符串以查看字符串失败的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9664593/