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; }
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.
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.