c++ - 使用 regex_search 获取所有匹配项的索引?

标签 c++ regex string c++11

我刚刚开始学习如何使用regex进行字符串处理(C++11新功能)。如果以下问题太愚蠢,请原谅我。

目前我应用以下代码来获取所有匹配项的索引:

string str = "aaabxxxaab";
regex rx("ab");

vector<int> index_matches; // results saved here (should be {2, 8})

int track = 0;
smatch sm;
while (regex_search(str, sm, rx))
{
    index_matches.push_back(track+sm.position());

    string tmp = sm.suffix().str();
    track += str.length() - tmp.length(); // update base index

    str = tmp;
}

它工作正常,但我必须每次手动更新track(基本索引)才能使其正常工作。

同时,我注意到已经有 smatch::size()smatch::position(),我想将它们组合起来使用来实现目标。以下是我想要将它们组合在一起但无法工作的代码(即始终仅获得 {2})。

string str = "aaabxxxaab";
regex rx("ab");

vector<int> index_matches; // results saved here 
                           // (should be {2, 8}, but always get only {2})

smatch sm;
regex_search(str, sm, rx);
for (int i=0; i<sm.size(); i++)
    index_matches.push_back(sm.position(i));

有人可以告诉我如何正确使用 smatch::size()smatch::position() 来获取所有匹配的索引吗?

最佳答案

单次执行 regex_search 只会为您提供一个匹配项(您查询的大小和位置)。

您可以:更改正则表达式以多次匹配子字符串(然后循环捕获组),或者仅使用regex_iterator

string str = "aaabxxxaab";
regex rx("ab");

vector<int> index_matches; // results saved here 
                           // (should be {2, 8}, but always get only {2})

for(auto it = std::sregex_iterator(str.begin(), str.end(), rx);
    it != std::sregex_iterator();
     ++it)
{
    index_matches.push_back(it->position());
}

在线演示:http://coliru.stacked-crooked.com/a/4d6e1a44b60b7da5

关于c++ - 使用 regex_search 获取所有匹配项的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21753899/

相关文章:

c++ - (Qt) QNetworkAccessManager 减慢其他应用程序

javascript - Google Scripts - 从退回的邮件中获取电子邮件地址并解析信息

c# - 如何仅匹配正则表达式中的第一个数字

regex - 如何使用 Spark 读取自定义多行日志

ios - @""的替代品?

c++ - 我是否正确地将枚举值与 C+ +'s "或“运算符”进行了比较?

c++ - 如何开始为 C++ 库编写 Perl 绑定(bind)?

java - 从.txt文件读取,只读取某些文档?

c++ - 在 C++ 中创建动态文件指针

javascript - 区分何时读取带有字符串的变量