6

RE2は、Googleから入手できる最新の正規表現エンジンです。現在gnuregexを使用しているプログラムでRE2を使用したい。私が抱えている問題は、何が一致するかを見つけることに関するものです。RE2が返すのは、一致した文字列です。一致したもののオフセットを知る必要があります。私の現在の計画は、RE2が返すものを取得してfindから、C++文字列でを使用することです。しかし、これは無駄に思えます。RE2のマニュアルを読みましたが、その方法がわかりません。何か案は?

4

1 に答える 1

11

結果をのre2::StringPiece代わりに保存しstd::stringます。の値は.data()元の文字列を指します。

このプログラムを検討してください。各テストで、は元のまたはresult.data()へのポインタです。const char*std::string

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


int main(void) {

  { // Try it once with character pointers
    const char *text[] = { "Once", "in", "Persia", "reigned", "a", "king" };

    for(int i = 0; i < 6; i++) {
      re2::StringPiece result;
      if(RE2::PartialMatch(text[i], "([aeiou])", &result))
        std::cout << "First lower-case vowel at " << result.data() - text[i] << "\n";
      else
        std::cout << "No lower-case vowel\n";
    }
  }

  { // Try it once with std::string
    std::string text[] = { "While", "I", "pondered,", "weak", "and", "weary" };

    for(int i = 0; i < 6; i++) {
      re2::StringPiece result;
      if(RE2::PartialMatch(text[i], "([aeiou])", &result))
        std::cout << "First lower-case vowel at " << result.data() - text[i].data() << "\n";
      else
        std::cout << "No lower-case vowel\n";
    }
  }
}
于 2012-08-12T09:20:00.993 に答える