c++ - 循环字符串以查看字符串失败的位置

标签 c++ regex string boost

我希望能够循环遍历正在根据正则表达式进行测试的字符串,以及它是否无法输出失败的字符串其余部分。

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/

相关文章:

c++ - 类 - 用户定义的具有动态大小的智能阵列

c++ - cmake 链接到静态库 - 你必须告诉 cmake 去哪里找吗?

c++ - operator new() 可以在构造函数运行之前初始化 POD 吗?

java - 为什么eclipse中仍然不显示汉字?

javascript - 从本地存储检索数据对象并将其重新加载到数组中

c++ - 找不到默认构造函数来初始化 cpp 中的成员

python - python 3 的可靠 isnumeric() 函数是什么?

正则表达式模式不适合赋值之类的代码

java - 提取匹配和不匹配的正则表达式

android - 如何在EditText中显示格式化文本?