see #12: translate ch06

This commit is contained in:
Changkun Ou
2019-07-16 09:30:56 +02:00
parent 9180aab4e6
commit 507f8b9673
17 changed files with 294 additions and 36 deletions

View File

@@ -3,8 +3,9 @@
// modern c++ tutorial
//
// created by changkun at changkun.de
// https://github.com/changkun/modern-cpp-tutorial
//
// 正则表达式库
// Regular Expression
#include <iostream>
#include <string>
@@ -12,7 +13,9 @@
int main() {
std::string fnames[] = {"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};
// C++ `\` 会被作为字符串内的转义符,为使 `\.` 作为正则表达式传递进去生效,需要对 `\` 进行二次转义,从而有 `\\.`
// In C++, `\` will be used as an escape character in the string.
// In order for `\.` to be passed as a regular expression,
// it is necessary to perform second escaping of `\`, thus we have `\\.`
std::regex txt_regex("[a-z]+\\.txt");
for (const auto &fname: fnames)
std::cout << fname << ": " << std::regex_match(fname, txt_regex) << std::endl;
@@ -21,8 +24,8 @@ int main() {
std::smatch base_match;
for(const auto &fname: fnames) {
if (std::regex_match(fname, base_match, base_regex)) {
// sub_match 的第一个元素匹配整个字符串
// sub_match 的第二个元素匹配了第一个括号表达式
// the first element of std::smatch matches the entire string
// the second element of std::smatch matches the first expression with brackets
if (base_match.size() == 2) {
std::string base = base_match[1].str();
std::cout << "sub-match[0]: " << base_match[0].str() << std::endl;