re2 で String#scan 的なことをする

C++ でかかれた 高速でつかいやすい正規表現エンジンである re2 で String#scan 的な操作をしたいとおもったのでやってみた。もっとスマートな解法がありそうですが、これでとりあえずうごきます。

だれかもっといいやり方しってたらおしえてください。

#include <iostream>
#include <string>
#include <re2/re2.h>

using namespace re2;

int main () {
    RE2 re(".a");
    std::string str("ablacadabla");

    int start = 0;
    int end = str.size();
    re2::StringPiece buf[1];
    while (re.Match(str, start, end, RE2::UNANCHORED, buf, 1)) {
        std::cout << "MATCH: " << buf[0].as_string() << std::endl;
        start = buf[0].data() - str.c_str() + buf[0].length();
    }
}

Published: 2012-03-27(Tue) 05:02