在字符串上循环以查看字符串失败的位置

looping over string to see where the string failed

本文关键字:字符串 失败 位置 循环      更新时间:2023-10-16

我希望能够在正针对正则表达式进行测试的字符串上循环,如果它未能输出它与字符串其余部分一起失败的地方。

boost::regex const string_matcher("[0-9]{5}");
if (boost::regex_match(12A45,string_matcher))
{
    DCS_LOG_DEBUG("Correctn");                     
}
else
{
    DCS_LOG_DEBUG("Incorrectn");
}

所以这个输出就是

"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

您可以做的是:

循环字符串中的字符,当结果不正确时进行循环时,使用indexof(chr)打印结果,其中chr是当前循环中的字符然后退出循环。