Tuesday, August 29, 2017

C++11: Regex: Global

You can globally search a string as if using the Perl ‘g’ mode switch. Here is an example.

#include <iostream>
#include <regex>
#include <string>
 
int main()
{
  std::string myString("aeiouaeiouaeiou");
  std::regex  myRegex ("aeiou");
  std::smatch myMatches;
  std::string mySuffix;
  bool        keepLooping = true;
 
  keepLooping = true    ;
  mySuffix    = myString;
 
  while (keepLooping)
  {
    keepLooping = std::regex_search(mySuffix, myMatches, myRegex);
    if (myMatches.size() > 0)
    {
      std::cout << myMatches.size() << " ";
      std::cout << myMatches[0] << std::endl;
    }
    mySuffix = myMatches.suffix();
  }
  return 0;
}
/* Output:
 1 aeiou
 1 aeiou
 1 aeiou
*/
Reference: http://www.cplusplus.com/reference/regex/regex_search/

No comments:

Post a Comment