2015-09-13 32 views
5

私はC++ regexを初めて使用しています。私は文字列 "{1,2,3}"を持っており、数字1 2 3を抽出したい。regex_searchを使うべきだと思ったが失敗した。C++ regex regex_search()を使用してすべての部分文字列を抽出します

#include<iostream> 
#include<regex> 
#include<string> 
using namespace std; 
int main() 
{ 
     string s1("{1,2,3}"); 
     string s2("{}"); 
     smatch sm; 
     regex e(R"(\d+)"); 
     cout << s1 << endl; 
     if (regex_search(s1,sm,e)){ 
       cout << "size: " << sm.size() << endl; 
       for (int i = 0 ; i < sm.size(); ++i){ 
         cout << "the " << i+1 << "th match" <<": "<< sm[i] << endl; 
       } 
     } 
} 

結果:実測値のみ最初試合後

{1,2,3} 
size: 1 
the 1th match: 1 
+0

あなたはおそらく[ 'regex_matchを()']使用したい(のhttp:/ /en.cppreference.com/w/cpp/regex/regex_match)に、この形式を説明する適切な式を入力します。 –

答えて

6

std::regex_search戻ります。

std::smatchは、正規表現内のすべての一致するグループです。正規表現には1つのグループしか含まれていないため、std::smatchには1つの項目しかありません。

すべての一致を検索する場合は、std::sregex_iteratorを使用する必要があります。

int main() 
{ 
    std::string s1("{1,2,3}"); 
    std::regex e(R"(\d+)"); 

    std::cout << s1 << std::endl; 

    std::sregex_iterator iter(s1.begin(), s1.end(), e); 
    std::sregex_iterator end; 

    while(iter != end) 
    { 
     std::cout << "size: " << iter->size() << std::endl; 

     for(unsigned i = 0; i < iter->size(); ++i) 
     { 
      std::cout << "the " << i + 1 << "th match" << ": " << (*iter)[i] << std::endl; 
     } 
     ++iter; 
    } 
} 

出力:iterは試合がなくなったとき、それはiterに等しくなるように

{1,2,3} 
size: 1 
the 1th match: 1 
size: 1 
the 1th match: 2 
size: 1 
the 1th match: 3 

endイテレータは、設計によって構築デフォルトです。ループの最下部には++iterがあります。それはiterを次の試合に移します。一致がなくなると、iterのデフォルト値はendと同じ値になります。

別の例submatchingを表示するには(キャプチャグループ):

int main() 
{ 
    std::string s1("{1,2,3}{4,5,6}{7,8,9}"); 
    std::regex e(R"~((\d+),(\d+),(\d+))~"); 

    std::cout << s1 << std::endl; 

    std::sregex_iterator iter(s1.begin(), s1.end(), e); 
    std::sregex_iterator end; 

    while(iter != end) 
    { 
     std::cout << "size: " << iter->size() << std::endl; 

     std::cout << "expression match #" << 0 << ": " << (*iter)[0] << std::endl; 
     for(unsigned i = 1; i < iter->size(); ++i) 
     { 
      std::cout << "capture submatch #" << i << ": " << (*iter)[i] << std::endl; 
     } 
     ++iter; 
    } 
} 

出力:

{1,2,3}{4,5,6}{7,8,9} 
size: 4 
expression match #0: 1,2,3 
capture submatch #1: 1 
capture submatch #2: 2 
capture submatch #3: 3 
size: 4 
expression match #0: 4,5,6 
capture submatch #1: 4 
capture submatch #2: 5 
capture submatch #3: 6 
size: 4 
expression match #0: 7,8,9 
capture submatch #1: 7 
capture submatch #2: 8 
capture submatch #3: 9 
+0

ありがとうございます。私は "終わり"が何であるか尋ねることができますか?あなたが初期化していないように見えます。 std :: sregex_iterator end; – daydayup

+0

@daydayup 'end'イテレータは、' iter'がマッチしなくなったときに 'iter'と等しくなるように、デフォルトで設計されています。ループの一番下にある '++ iter'を見てください。それが次の試合に移ります。一致するものがなくなると、 'iter'はデフォルトで構築された' end'と同じ値を持ちます。サブミッチングを表示する別の例を追加しました。 – Galik

+0

これは非常に参考になる例です!ありがとうございました – daydayup

関連する問題