0

Below is my following code

#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";
    }
}

It always outputs with no Matches.

Im sure that regex should work.

I used this example

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

Angel.King.47
  • 7,922
  • 14
  • 60
  • 85

2 Answers2

3

from boost regex:

Important

Note that the result is true only if the expression matches the whole of the input sequence. If you want to search for an expression somewhere within the sequence then use regex_search. If you want to match a prefix of the character string then use regex_search with the flag match_continuous set.

chris
  • 3,986
  • 1
  • 26
  • 32
0

Try boost::regex re("(.*)name(.*)"); if you want to use the expression with regex_match.

rturrado
  • 7,699
  • 6
  • 42
  • 62
  • Would that return 2x `name` if my string would be `Hello my name is bob name` – Angel.King.47 Nov 15 '10 at 12:26
  • That would return: for `Hello my name is bob`, two matches: `Hello my`, and `is bob`. And for `Hello my name is bob name`, one match: `Hello my name is bob`. – rturrado Nov 15 '10 at 13:15