-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-regex.cc
59 lines (51 loc) · 1.7 KB
/
04-regex.cc
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// Program
// Regular Expression: Replace an expression
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -o 04-regex 04-regex.cc
//
// Execution
// ./04-regex
//
#include <iostream>
#include <iomanip>
#include <regex>
#include <vector>
//
// Entry function
//
int main() {
{
// Find start and end tags:
// - <START_TAG> text </ END_TAG>
// - start and end tags can be anywhere in the long sentence
// - start end end tags must have same text
std::regex re(R"(<(.*)>.*<\/(\1)>)");
std::vector<std::string> input_texts = {
{ R"(<start>C++ Regex</start>)" },
{ R"(<start>C++ Regex</end>)" },
{ R"(<title>C++ Regex</title>)" },
{ R"(<title>C++ Regex title>)" },
{ R"(<title C++ Regex</title>)" },
{ R"(sdummy<title>C++ Regex</title>)" },
{ R"(<title>C++ Regex</title>edummy)" },
{ R"(sdummy<title>C++ Regex</title>edummy)" },
};
std::cout << '\n'
<< "---- " << "Find start/end tag" << " ----"
<< '\n' << '\n';
// Ref: https://www.boost.org/doc/libs/1_46_1/libs/regex/doc/html/boost_regex/format.html explains mapping fmt
std::string new_s;
for (const auto& input: input_texts) {
std::cout << '\n' << "- " << input << '\n';
new_s = std::regex_replace(input, re, "[$&]"); // $& wrapped matched char sequence in [ ]
std::cout << "> " << new_s << '\n';
new_s = std::regex_replace(input, re, "[$']"); // $' wrapped char sequence after our matched string in [ ]
std::cout << "> " << new_s << '\n';
new_s = std::regex_replace(input, re, "[$`]"); // $' wrapped char sequence before our matched string in [ ]
std::cout << "> " << new_s << '\n';
}
}
return 0;
}