Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tokenize strings using std::regex library in Visual Studio 2010?

Tags:

c++

regex

c++11

stl

I could not find the reference of std::regex library. I did some google searches and found some tutorials, but they're all brief and short. I couldn't figure out how to tokenize a string using regex.

Could anyone give me a hint how to start?

like image 941
Chan Avatar asked Dec 22 '10 18:12

Chan


2 Answers

A video tutorial on STL regular expressions.

like image 153
Adrian McCarthy Avatar answered Sep 28 '22 06:09

Adrian McCarthy


#include <regex>
#include <iostream>
#include <string>


void ifIWantASpecificMatch ()
{
   const std::string input = "Hello World";
   const std::regex regex("(.*) (.*)");

   std::smatch match; // std::match_result ready templated for std::string

   if (std::regex_match(input, match, regex)) {
      std::cout << "full match " << match[0] << std::endl;
      std::cout << "first group " << match[1] << 
      " beginning at: " << match[1].first - input.begin() << std::endl;
      std::cout << "second group " << match[2] << 
         " beginning at: " << match[2].first - input.begin() << std::endl;
   }
}


void ifIWantToIterateAllMatches ()
{
   const std::string input = "I want to get all the o's";
   const std::regex regex("o");

   std::smatch match;

   for (std::sregex_iterator it(input.begin(), input.end(), regex), end; it != end; ++it) {
      std::cout << "Found at: " << it->position() << std::endl;
   }
}
like image 20
Marco Kinski Avatar answered Sep 28 '22 06:09

Marco Kinski