2011-11-27 8 views
9

C++ 11のstd::regexを使用して一致数を数えるにはどうすればよいですか?一致件数

std::regex re("[^\\s]+"); 
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl; 

予想される出力:

7

+2

そして、あなたの出力がある.... –

+0

@EdHeal私は、[コンパイルエラー](http://ideone.com/uxyrV)を取得します: 'error: 'regex_count'はこのスコープで宣言されていませんでした。 ;) –

答えて

15

あなたがそれらをカウントする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; 
+0

'std :: sregex_iterator'が返すものと、2つの手段の間の距離の説明を教えてください。 –

+1

@muntoo: 'sregex_iterator'は' regex_iterator'のtypedefです。これはテキスト中のすべての一致を繰り返します。 'distance'は、イテレータ範囲内の要素の数を計算する標準ライブラリ関数です(この場合、すべての一致を読み込み、そこに含まれる数を返します)。 –

+0

こんにちは。もしこれが古いスレッドであっても、(w)sregex :: iteratorは既にマッチしているように、あなた自身のことを繰り返しているので、match_countオペレーション(C++ 11では存在しない)を落とすことができると思います。したがって、std :: distanceは一致カウントを返します。私はmatch_countなしでgcc 4.6.1とVS 2013を使って試しました。うまくいきます。 – gilgamash

3

あなたは、この使用することができます:

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 
関連する問題