tags:

views:

324

answers:

3

I want to return output "match" if the pattern "regular" is a sub-string of variable st. Is this possible?

int main()
{
  string st = "some regular expressions are Regxyzr";

  boost::regex ex("[Rr]egular");
  if (boost::regex_match(st, ex)) 
  {
    cout << "match" << endl;
  }
  else 
  {
    cout << "not match" << endl;
  }
}
+5  A: 

The boost::regex_match only matches the whole string, you probably want boost::regex_search instead.

Michael Anderson
+4  A: 

regex_search does what you want; regex_match is documented as

determines whether a given regular expression matches all of a given character sequence

(the emphasis is in the original URL I'm quoting from).

Alex Martelli
A: 

Your question is answered with example in library documentation - boost::regex

Alternate approach:

You can use boost::regex_iterator, this is useful for parsing file etc.

string[0], 
string[1] 

below indicates start and end iterator.

Ex:

boost::regex_iterator stIter(string[0], string[end], regExpression)
boost::regex_iterator endIter

for (stIter; stIter != endIter; ++stIter)
{
   cout << " Whole string " << (*stIter)[0] << endl;
   cout << " First sub-group " << (*stIter)[1] << endl;
}

}

Ketan