Skip navigation

Tag Archives: boost

First, Install Boost and be sure to choose the regex package when you install it.

Regex matching in C++ using BOOST

Regex replace in C++ using BOOST

Regex extract in C++ using BOOST

See example below.

#include <iostream>
#include <string>
#include <boost/regex.hpp> // add boost regex library
using namespace std ;

int main()
{
  // http://www.boost.org/doc/libs/1_35_0/more/getting_started/windows.html#get-boost

  // To practice regular expressions, use
  // http://weitz.de/regex-coach/
  bool quitting = false ;
  string input ;

  puts( " *** Regex MATCH test ***" ) ;
  puts( " ------------------------" ) ;
  while( !quitting )
  {
    boost::regex EXPR( "[0-9][0-9][A-Za-z]" ) ;

    cout << "The expression is:" << endl ;
    cout << EXPR << endl << endl ;
    
    cout << "Enter a string to match it, or just type Q to move on" << endl ;
    getline( cin, input ) ;

    bool matches = boost::regex_match( input, EXPR ) ;
    if( matches )
    {
      puts( "Congrats, you entered a string that matches the expression." ) ;
    }
    else if( input == "q" || input == "Q" )
    {
      puts( "Bye!" ) ;
      quitting = true ;
    }
    else
    {
      puts( "NO, that string didn't match" ) ;
    }
  }

  puts( "\n" ) ;
  puts( " *** Regex REPLACE test ***" ) ;
  puts( " --------------------------" ) ;
  quitting = false ;
  
  while( !quitting )
  {
    boost::regex EXPR( "e" ) ;
    string REPLACEMENT = "X" ;

    cout << "I am replacing: " << EXPR << " with: " << REPLACEMENT << endl ;
    cout << EXPR << endl << endl ;
    
    cout << "Enter a string with lowercase 'e' in it, or just type Q to quit." << endl ;
    getline( cin, input ) ;

    if( input == "q" || input == "Q" )
    {
      puts( "Bye!" ) ;
      quitting = true ;
    }
    else
    {
      string replaced = boost::regex_replace( input, EXPR, REPLACEMENT, boost::match_default | boost::format_sed ) ;
      cout << replaced << endl;
    }
  }


  // Finally, a test showing capturing
  boost::regex EXPR( "<food>([A-Za-z]+)</food>" ) ;
  string xmlData = "<food>pizza</food>" ;

  string replaced = boost::regex_replace(
    
    xmlData,  // the data
    
    EXPR,     // the regex

    "\\1",    // Don't forget to DOUBLE backslash
              // your regex escape sequences!!

    boost::match_default | boost::format_sed
    // You can get perl-style regex strings,
    // "sed" style regex strings,
    // or you can use boost's own 
    // extended format style strings.
    // See http://www.boost.org/doc/libs/1_33_1/libs/regex/doc/format_syntax.html
  ) ;
  cout << "EXPR: " << EXPR << endl;
  cout << "Data: " << xmlData << endl;
  cout << "The extracted data was: " << replaced << endl ;
}
Advertisements