Source of regex_substitution.cpp


  1: //regex_substitution.cpp (based on a Deitel example)
  2: //Illustrates use of the regex_replace algorithm.

  4: #include <iostream>
  5: #include <string>
  6: using namespace std;

  8: #include "boost/regex.hpp"
  9: using boost::regex;
 10: using boost::regex_replace;
 11: using boost::sregex_token_iterator;
 12: using boost::format_first_only;

 14: int main()
 15: {
 16:     //Set up a first test string
 17:     string testString1 = "This sentence ends in 5 stars *****.";
 18:     cout << "\nFirst original string: " << testString1 << endl;

 20:     //Replace every * in this first test string with a ^
 21:     testString1 = regex_replace(testString1, regex("\\*"), "^");
 22:     cout << "^ substituted for *: " << testString1 << endl;

 24:     //Next, replace "stars" with "carets" in the first test string
 25:     testString1 = regex_replace(testString1, regex("stars"), "carets");
 26:     cout << "\"carets\" substituted for \"stars\": "
 27:         << testString1 << endl;

 29:     //Finally, replace every word with "word" in the first test string
 30:     testString1 = regex_replace(testString1, regex("\\w+"), "word" );
 31:     cout << "Every word replaced by \"word\": " << testString1 << endl;

 33:     //Set up a second test string
 34:     string testString2 = "1, 2, 3, 4, 5, 6, 7, 8";
 35:     cout << "\nSecond original string: " << testString2 << endl;

 37:     //Replace the first three digits with "digit" in the 2nd test string
 38:     string testString2Copy = testString2;
 39:     for (int i = 0; i < 3; i++ ) //Loop three times
 40:         testString2Copy = regex_replace(testString2Copy,
 41:             regex("\\d" ), "digit", format_first_only );
 42:     cout << "First 3 digits replaced by \"digit\": "
 43:         << testString2Copy << endl;

 45:     //Next, split the second test string at the commas
 46:     cout << "String split at commas [";

 48:     sregex_token_iterator tokenIterator(testString2.begin(),
 49:         testString2.end(), regex(",\\s" ), -1 ); //token iterator
 50:     //The -1 means point at what *doesn't" match the regex.
 51:     sregex_token_iterator end; //Default iterator acts as terminator value
 52:     //Analogous to the default constructor for an input stream iterator

 54:     string output;
 55:     while (tokenIterator != end) //tokenIterator isn't empty
 56:     {
 57:         output += "\"" + *tokenIterator + "\", "; //Add token to output
 58:         tokenIterator++; //Advance the iterator
 59:     }
 60:     //Finally, delete the ", " at the end of output string
 61:     cout << output.substr(0, output.length() - 2 ) << "]" << endl;
 62:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 63: }