MCPcopy Create free account
hub / github.com/changkun/modern-cpp-tutorial / main

Function main

code/6/6.1.cpp:13–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11#include <regex>
12
13int main() {
14 std::string fnames[] = {"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};
15 // 在 C++ 中 `\` 会被作为字符串内的转义符,为使 `\.` 作为正则表达式传递进去生效,需要对 `\` 进行二次转义,从而有 `\\.`
16 std::regex txt_regex("[a-z]+\\.txt");
17 for (const auto &fname: fnames)
18 std::cout << fname << ": " << std::regex_match(fname, txt_regex) << std::endl;
19
20 std::regex base_regex("([a-z]+)\\.txt");
21 std::smatch base_match;
22 for(const auto &fname: fnames) {
23 if (std::regex_match(fname, base_match, base_regex)) {
24 // sub_match 的第一个元素匹配整个字符串
25 // sub_match 的第二个元素匹配了第一个括号表达式
26 if (base_match.size() == 2) {
27 std::string base = base_match[1].str();
28 std::cout << "sub-match[0]: " << base_match[0].str() << std::endl;
29 std::cout << fname << " sub-match[1]: " << base << std::endl;
30 }
31 }
32 }
33
34 return 0;
35}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected