2010-11-15 36 views
0

下面是我下面的代碼正則表達式和提升。不工作的一個簡單的正則表達式

#include <iostream> 
#include <stdlib.h> 
#include <boost/regex.hpp> 
#include <string> 
using namespace std; 
using namespace boost; 

int main() { 

    std::string s = "Hello my name is bob"; 
    boost::regex re("name"); 
    boost::cmatch matches; 

    try{ 

     // if (boost::regex_match(s.begin(), s.end(), re)) 
     if (boost::regex_match(s.c_str(), matches, re)){ 

      cout << matches.size(); 

      // matches[0] contains the original string. matches[n] 
      // contains a sub_match object for each matching 
      // subexpression 
      for (int i = 1; i < matches.size(); i++){ 
       // sub_match::first and sub_match::second are iterators that 
       // refer to the first and one past the last chars of the 
       // matching subexpression 
       string match(matches[i].first, matches[i].second); 
       cout << "\tmatches[" << i << "] = " << match << endl; 
      } 
     } 
     else{ 
      cout << "No Matches(" << matches.size() << ")\n"; 
     } 
    } 
    catch (boost::regex_error& e){ 
     cout << "Error: " << e.what() << "\n"; 
    } 
} 

它總是不匹配輸出。

我確定正則表達式應該可以工作。

我用這個例子

http://onlamp.com/pub/a/onlamp/2006/04/06/boostregex.html?page=3

回答

3

boost regex

重要

注意,結果爲真只有當表達式整個輸入序列的匹配。如果您想要在序列中的某處搜索表達式,請使用regex_search。如果你想匹配字符串的前綴,那麼使用帶有match_continuous標誌的regex_search。

+0

謝謝,我剛剛意識到這一點。將for循環移出。我會接受 – 2010-11-15 12:07:56

0

如果您想使用regex_match的表達式,請嘗試boost::regex re("(.*)name(.*)");

+0

如果我的字符串是'你好,我的名字是bob名字',會返回2個'name'嗎? – 2010-11-15 12:26:16

+0

這將返回:對於'你好,我的名字是bob',兩個匹配:'你好我的','是bob'。對於'你好我的名字是鮑勃名字',一個匹配:'你好,我的名字是鮑勃'。 – rturrado 2010-11-15 13:15:08

相關問題