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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i just realized that as well. moved the for loop out. Thanks i will accept
0

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

2 Comments

Would that return 2x name if my string would be Hello my name is bob name
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.