在字符串上循环以查看字符串失败的位置
looping over string to see where the string failed
我希望能够在正针对正则表达式进行测试的字符串上循环,如果它未能输出它与字符串其余部分一起失败的地方。
即
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是当前循环中的字符然后退出循环。
相关文章:
- 使用提升对字符串进行标记化时,将令牌转换为 char* const* 时失败
- std::p作为 std 中定义的unordered_map自定义键的字符串的空气失败并出现模板错误
- C++ TCP 服务器比较字符串失败
- 嵌套列表(字符串向量的向量)初始化失败
- C++长到字符串的转换失败
- 字符串流运算符输入失败
- AES/CFB密码模式从字符串失败中解密
- 增强精神解析报价字符串失败
- BOOST :: lexical_cast to std ::字符串失败
- 假定相同的字符串之间的比较失败' == '比较
- 如何在类中存储指向字符串到成员函数映射的智能指针,以便它不会因类型不完整而失败?
- 从文件中提取的数据中的C 搜索字符串失败
- C++:为什么这个字符串输入失败,而另一个没有
- 失败的证明转换字符串到枚举类
- 当Find_first_not_of击中字符串末尾时,为什么会失败
- C++ 使用字符串时运行失败
- 在字符串上循环以查看字符串失败的位置
- 当显式调用非默认函数时,覆盖自定义字符串失败
- DCOM中的SAFEARRAY(BSTR) as [out]参数返回字符串失败
- 从函数返回本地var字符串失败,而本地var int和char工作正常.为什么