summaryrefslogtreecommitdiff
path: root/regex-replace-example.cpp
blob: 08c242011bb87c5f3bf66814d792bf55c268b125 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// regex_replace example
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

using namespace std;

int main ()
{
  string s ("hello wherever wholly heroic howlling herring");

  // find words starting with 'he'.
  // words containing 'he' not at the beginning should not be replaced.
  regex e ("\\bhe");

  // replace ALL 'he' with 'HE'
  // (only in
  cout << "upper-case HE (all): "
       << regex_replace(s,e,"HE")
       << endl;

  // replace just one (the first) 'he with 'HE'
  cout << "upper-case HE (one): "
       << regex_replace(s,e,"HE", regex_constants::format_first_only)
       << endl;


  string s2("hello world");
  // find two words separated by spaces
  regex e2("(\\w+)\\s+(\\w+)");
  // Replace their order
  cout << "swapped words: "
       << regex_replace (s2,e2,"$2 $1")
       << endl;

  return 0;
}