Debian Codegraph @

yo/stl/examples/regexreplace.cc

raw
1 #include <string>
2 #include <iostream>
3 #include <regex>
4 #include <iterator>
5
6 using namespace std;
7
8 bool modify(string const &match)
9 {
10 cout << "Capitalize and *-embed " << match << " [yn]? ";
11 string request;
12 getline(cin, request);
13 return request == "y";
14 }
15
16 size_t replace(string &target, string::iterator begin, string match)
17 {
18 for (auto &el: match)
19 el = toupper(el);
20 size_t len = match.length();
21 match = '*' + match + '*';
22 target.replace(begin, begin + len, match);
23
24 return len + 2;
25 }
26
27 int main()
28 {
29 string target("... oh, when the Saints, ...");
30
31 regex re("\\w+");
32 smatch match;
33 size_t offset = 0;
34 while (true)
35 {
36 auto begin = target.begin() + offset;
37 if (not regex_search(string::const_iterator(begin),
38 target.cend(), match, re))
39 break;
40
41 size_t pos = match.position(0);
42
43 offset += pos +
44 (modify(match[0]) ?
45 replace(target, begin + pos, match[0])
46 :
47 match.length(0));
48 }
49 cout << "new text: " << target << '\n';
50 }
51 //=