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

4

2 回答 2

3

升压正则表达式

重要的

请注意,仅当表达式与整个输入序列匹配时,结果才为真。如果要在序列中的某处搜索表达式,请使用 regex_search。如果要匹配字符串的前缀,则使用带有标志 match_continuous 集的 regex_search。

于 2010-11-15T12:05:27.393 回答
0

boost::regex re("(.*)name(.*)");如果您想将表达式与 一起使用,请尝试regex_match

于 2010-11-15T12:11:53.610 回答