【问题标题】:Get the index of all matches using regex_search?使用 regex_search 获取所有匹配项的索引?
【发布时间】:2014-02-13 12:11:37
【问题描述】:

我刚刚开始学习如何使用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() 来获取所有匹配的索引?

【问题讨论】:

    标签: c++ regex string c++11


    【解决方案1】:

    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

    【讨论】:

    • 你有什么参考书/书可以让我开始学习regex吗?
    • @herohuyongtao cppreference 有一个不错的阐述,如果你具体询问 C++ 的 &lt;regex&gt;
    • 谢谢。我会调查的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2013-10-30
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多