boost :: regex_matchを使用していて、正規表現が一致しなくなった位置を取得する関数を見つけようとしています。boost :: match_resultsオブジェクトに属性が見つかりませんでしたが、boost::regex_searchを使用してサブマッチを表示するいくつかのコードスニペットが見つかりました。私は自分の実装で正しい道を進んでいますか、それともそれを達成するために何か別のことをしなければなりませんか?私のコードは次のようになります。
int main(int args, char** argv)
{
boost::match_results<std::string::const_iterator> what;
if(args == 3)
{
std::string text(argv[1]);
boost::regex expression(argv[2]);
std::cout << "Text : " << text << std::endl;
std::cout << "Regex: " << expression << std::endl;
if(boost::regex_match(text, what, expression, boost::match_default) != 0)
{
int i = 0;
for(boost::match_results<std::string::const_iterator>::const_iterator it=what.begin(); it!=what.end(); ++it)
{
std::cout << "[" << (i++) << "] " << it->str() << std::endl;
}
std::cout << "Matched!" << std::endl;
}
else
{
std::string::const_iterator start = text.begin();
std::string::const_iterator end = text.end();
while(boost::regex_search(start, end, what, expression))
{
std::string submatch(what[1].first, what[1].second);
std::cout << submatch << std::endl;
start = what[0].second;
}
std::cout << "Didn't match!" << std::endl;
}
} //if(args == 3)
else
{
std::cout << "Invalid usage! $> ./boost-regex <text> <regex>" << std::endl;
}
return 0;
}
出力:
$> ./boost_regex "We're building it up to burn it down" ".*(build.*)(to.*)(burn.*)"
Text : We're building it up to burn it down
Regex: .*(build.*)(to.*)(burn.*)
[0] We're building it up to burn it down
[1] building it up
[2] to
[3] burn it down
Matched!
$> ./boost_regex "We're building it up to burm it down" ".*(build.*)(to.*)(burn.*)"
Text : We're building it up to burm it down
Regex: .*(build.*)(to.*)(burn.*)
Didn't match!
最後の入力については、次のようなものが必要です。
Text : We're building it up to burm it down
Regex: .*(build.*)(to.*)(burn.*)
[0] We're building it up to
[1] building it up
[2] to
Didn't match!
前もって感謝します ...