Replacing and Splitting Strings with regular expressions using regex_replace algorithm. - C++ Regular Expression

C++ examples for Regular Expression:Replace

Description

Replacing and Splitting Strings with regular expressions using regex_replace algorithm.

Demo Code

#include <iostream> 
#include <string> 
#include <regex> 
using namespace std; 

int main() //  w ww .j  a  v  a  2  s. c o  m
{ 
   // create the test strings 
   string testString1 = "thi s is a test. This sentence ends in 5 stars *****"; 
   string testString2 = "1, 2, 3, 4, 5, 6, 7, 8"; 
   string output; 

   cout << "Original string: " << testString1 << endl; 

   // replace every * with a ^ 
   testString1 = regex_replace( testString1, regex( "\\*" ), string( "^" ) ); 
   cout << "^ substituted for *: " << testString1 << endl; 

   // replace "stars" with "carets" 
   testString1 = regex_replace( testString1, regex( "stars" ), string( "carets" ) ); 
   cout << "\"carets\" substituted for \"stars\": " << testString1 << endl; 

   // replace every word with "word" 
   testString1 = regex_replace( testString1, regex( "\\w+" ), string( "word" ) ); 
   cout << "Every word replaced by \"word\": " << testString1 << endl; 

   // replace the first three digits with "digit" 
   cout << "\nOriginal string: " << testString2 << endl; 
   string testString2Copy = testString2; 

   for ( int i = 0; i < 3; ++i ) // loop three times 
   { 
       testString2Copy = regex_replace( testString2Copy, regex( "\\d" ), "digit", regex_constants::format_first_only ); 
   }

   cout << "Replace first 3 digits by \"digit\": " << testString2Copy << endl; 

   // split the string at the commas 
   cout << "string split at commas ["; 

   regex splitter( ",\\s" ); // regex to split a string at commas 
   sregex_token_iterator tokenIterator( testString2.begin(), testString2.end(), splitter, -1 ); // token iterator 
   sregex_token_iterator end;  // empty iterator 

   while ( tokenIterator != end ) // tokenIterator isn't empty 
   { 
       output += "\"" + (*tokenIterator).str() + "\", "; 
       ++tokenIterator; // advance the iterator 
   }

   // delete the ", " at the end of output string 
   cout << output.substr( 0, output.length() - 2 ) << "]" << endl; 
} // end of function main

Result


Related Tutorials