2010-11-15 33 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

相关问题