C++ 11のstd::regex
を使用して一致数を数えるにはどうすればよいですか?一致件数
std::regex re("[^\\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
予想される出力:
7
C++ 11のstd::regex
を使用して一致数を数えるにはどうすればよいですか?一致件数
std::regex re("[^\\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
予想される出力:
7
あなたがそれらをカウントするdistance
を使用し、その後、試合の全てを生成するregex_iterator
を使用することができます。
std::regex const expression("[^\\s]+");
std::string const text("Harry Botter - The robot who lived.");
std::ptrdiff_t const match_count(std::distance(
std::sregex_iterator(text.begin(), text.end(), expression),
std::sregex_iterator()));
std::cout << match_count << std::endl;
'std :: sregex_iterator'が返すものと、2つの手段の間の距離の説明を教えてください。 –
@muntoo: 'sregex_iterator'は' regex_iterator'のtypedefです。これはテキスト中のすべての一致を繰り返します。 'distance'は、イテレータ範囲内の要素の数を計算する標準ライブラリ関数です(この場合、すべての一致を読み込み、そこに含まれる数を返します)。 –
こんにちは。もしこれが古いスレッドであっても、(w)sregex :: iteratorは既にマッチしているように、あなた自身のことを繰り返しているので、match_countオペレーション(C++ 11では存在しない)を落とすことができると思います。したがって、std :: distanceは一致カウントを返します。私はmatch_countなしでgcc 4.6.1とVS 2013を使って試しました。うまくいきます。 – gilgamash
あなたは、この使用することができます:
をint countMatchInRegex(std::string s, std::string re)
{
std::regex words_regex(re);
auto words_begin = std::sregex_iterator(
s.begin(), s.end(), words_regex);
auto words_end = std::sregex_iterator();
return std::distance(words_begin, words_end);
}
使用例:
std::cout << countMatchInRegex("Harry Botter - The robot who lived.", "[^\\s]+");
出力:
7
そして、あなたの出力がある.... –
@EdHeal私は、[コンパイルエラー](http://ideone.com/uxyrV)を取得します: 'error: 'regex_count'はこのスコープで宣言されていませんでした。 ;) –