tags:

views:

392

answers:

2

Dear all,

From the following code, I expect to get this output from the corresponding input:

Input: FOO     Output: Match
Input: FOOBAR  Output: Match
Input: BAR     Output: No Match
Input: fOOBar  Output: No Match

But why it gives "No Match" for input FOOBAR?

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;


int main  ( int arg_count, char *arg_vec[] ) {
   if (arg_count !=2 ) {
       cerr << "expected one argument" << endl;
       return EXIT_FAILURE;
   }

   string InputString = arg_vec[1];
   string toMatch = "FOO";

   const regex e(toMatch);
   if (regex_match(InputString, e,match_partial)) {
       cout << "Match" << endl;
   } else {
       cout << "No Match" << endl;
   }


   return 0;
}

Update:

Finally it works with the following approach:

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;

bool testSearchBool(const boost::regex &ex, const string st) {
    cout << "Searching " << st << endl;
    string::const_iterator start, end;
    start = st.begin();
    end = st.end();
    boost::match_results<std::string::const_iterator> what;
    boost::match_flag_type flags = boost::match_default;
    return boost::regex_search(start, end, what, ex, flags);
}


int main  ( int arg_count, char *arg_vec[] ) {
    if (arg_count !=2 ) {
        cerr << "expected one argument" << endl;
        return EXIT_FAILURE;
    }

    string InputString = arg_vec[1];
    string toMatch = "FOO*";

    static const regex e(toMatch);
    if ( testSearchBool(e,InputString) ) {
        cout << "MATCH" << endl;
    }
    else {
         cout << "NOMATCH" << endl;
    }

    return 0;
}
+1  A: 

Your regular expression has to account for characters at the beginning and end of the sub-string "FOO". I'm not sure but "FOO*" might do the trick

match_partial would only return true if the partial string was found at the end of the text input, not the beginning.

A partial match is one that matched one or more characters at the end of the text input, but did not match all of the regular expression (although it may have done so had more input been available)

So FOOBAR matched with "FOO" would return false. As the other answer suggests, using regex.search would allow you to search for sub-strings more effectively.

Gayan
@Gayan: I tried, string toMatch = "FOO*"; It still doesn't match.
neversaint
It was just a hunch. I don't have the luxury of writing a test app using boost. Sorry
Gayan
This isn't shell expansion. "FOO*" would be an 'F', followed by an 'O', followed by zero or more 'O's.
Svante
Yep. I thought so. I don't remember much about regular expressions. FOO[a-z]*[A-Z]*?
Gayan
A: 

Use regex_search instead of regex_match.

Svante