added link to regex_search
← Older revision
Revision as of 23:24, 11 January 2013
(2 intermediate revisions by one user not shown)
Line 119:
Line 119:
int main()
int main()
{
{
−
std::string fnames[] = {"foo.txt", "bar.txt", "zoidberg"};
+
// Simple regular expression matching
−
+
std::string fnames[] = {"foo.txt", "bar.txt
", "baz.dat
", "zoidberg"};
std::regex txt_regex("[a-z]+\\.txt");
std::regex txt_regex("[a-z]+\\.txt");
+
for (const auto &fname : fnames) {
for (const auto &fname : fnames) {
std::cout
std::cout
+
}
+
+
// Extraction of a sub-match
+
std::regex base_regex("([a-z]+)\\.txt");
+
std::smatch base_match;
+
+
for (const auto &fname : fnames) {
+
if (std::regex_match(fname, base_match, base_regex)) {
+
// The first sub_match is the whole string; the next
+
// sub_match is the first parenthesized expression.
+
if (base_match.size() == 2) {
+
std::ssub_match base_sub_match = base_match[1];
+
std::string base = base_sub_match.str();
+
std::cout
+
}
+
}
}
}
+
+
// Extraction of several sub-matches
+
std::regex pieces_regex("([a-z]+)\\.([a-z]+)");
+
std::smatch pieces_match;
+
+
for (const auto &fname : fnames) {
+
if (std::regex_match(fname, pieces_match, pieces_regex)) {
+
std::cout
+
for (size_t i = 0; i
+
std::ssub_match sub_match = pieces_match[i];
+
std::string piece = sub_match.str();
+
std::cout
+
}
+
}
+
}
}
}
| output=
| output=
foo.txt: 1
foo.txt: 1
bar.txt: 1
bar.txt: 1
+
baz.dat: 0
zoidberg: 0
zoidberg: 0
+
foo.txt has a base of foo
+
bar.txt has a base of bar
+
foo.txt
+
submatch 0: foo.txt
+
submatch 1: foo
+
submatch 2: txt
+
bar.txt
+
submatch 0: bar.txt
+
submatch 1: bar
+
submatch 2: txt
+
baz.dat
+
submatch 0: baz.dat
+
submatch 1: baz
+
submatch 2: dat
}}
}}
Line 136:
Line 183:
{{dcl list template | cpp/regex/dcl list basic_regex}}
{{dcl list template | cpp/regex/dcl list basic_regex}}
{{dcl list template | cpp/regex/dcl list match_results}}
{{dcl list template | cpp/regex/dcl list match_results}}
+
{{dcl list template | cpp/regex/dcl list regex_search}}
{{dcl list end}}
{{dcl list end}}