2011-09-05 7 views
10

私はboost regexを使ってテキストファイルから部分集合を抽出しようとしています。現在、有効なメールアドレスの代わりに最初の有効な行とフルラインのみを返しています。私はイテレータを使い、サブマップを使ってみたが、成功しなかった。現在のコードは次のとおりです。C++でboost regexを使って部分集合を抽出する

if(Myfile.is_open()) { 
    boost::regex pattern("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"); 
    while(getline(Myfile, line)) { 
      string::const_iterator start = line.begin(); 
      string::const_iterator end = line.end(); 
      boost::sregex_token_iterator i(start, end, pattern); 
      boost::sregex_token_iterator j; 
      while (i != j) { 
      cout << *i++ << endl; 

    } 
    Myfile.close(); 
} 

答えて

16

boost::smatchを使用してください。

boost::regex pattern("what(ever) ..."); 
boost::smatch result; 
if (boost::regex_search(s, result, pattern)) { 
    string submatch(result[1].first, result[1].second); 
    // Do whatever ... 
} 
+0

多分私のRegexは間違っていますが、それは私にとって適切な結果をもたらさないのです。 – John

+0

正規表現でした、ありがとう。 – John

13
const string pattern = "(abc)(def)"; 
const string target = "abcdef"; 

boost::regex regexPattern(pattern, boost::regex::extended); 
boost::smatch what; 

bool isMatchFound = boost::regex_match(target, what, regexPattern); 
if (isMatchFound) 
{ 
    for (unsigned int i=0; i < what.size(); i++) 
    { 
     cout << "WHAT " << i << " " << what[i] << endl; 
    } 
} 

出力は次の

WHAT 0 abcdef 
WHAT 1 abc 
WHAT 2 def 

ブーストは、括弧で囲まれたサブマッチを使用して、最初のサブマッチは、常に完全マッチした文字列です。 regex_matchは入力行全体をパターンとマッチさせる必要があります。部分文字列をマッチさせる場合はregex_searchを使用してください。

上記の例では、boost :: regex :: extendedパラメータを使用して指定されたposix拡張正規表現構文を使用しています。このパラメータを省略すると、perl形式の正規表現構文を使用するように構文が変更されます。他の正規表現構文も利用できます。

関連する問題