蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 <regex> 整串匹配与原始字符串、smatch/cmatch 捕获组、sregex_iterator 遍历与替换标志

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-regex.cpp
explore-cpp-libs-regex.cpp156 行
#include <cstdio>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

int main() {
    std::vector<lab::Case> cases;

    // Case 1: regex_match with escaped backslash, raw string literal, anchors, quantifiers, alternation
    std::regex re_digits("\\d+");
    std::regex re_raw(R"(\d{2,4})");
    std::regex re_greet("^[a-zA-Z]+, [a-zA-Z]+!$");
    std::regex re_alt("cat|dog");
    std::regex re_dot("a.c");
    std::regex re_word(R"(\w+\s+[A-Z]+)");
    std::regex re_quant(R"(a*b?c+(ab)+)");
    bool ok1 = std::regex_match("12345", re_digits)
        && !std::regex_match("123ab", re_digits)
        && std::regex_match("2026", re_raw)
        && std::regex_match("Hello, World!", re_greet)
        && std::regex_match("cat", re_alt)
        && std::regex_match("dog", re_alt)
        && std::regex_match("abc", re_dot)
        && std::regex_match("key_1   XYZ", re_word)
        && std::regex_match("ccabab", re_quant);
    cases.push_back({
        "regex_match_and_raw_string",
        lab::jbool(true),
        lab::jbool(ok1),
        ok1
    });

    // Case 2: regex_search with smatch, cmatch, cregex_iterator & syntax_option_type::icase
    std::string text = "user=Alice id=42";
    std::regex re_kv(R"(user=(\w+)\s+id=(\d+))");
    std::smatch sm;
    bool hit_s = std::regex_search(text, sm, re_kv);
    const char* ctext = "CODE:ab12 CODE:cd34";
    std::regex re_c("code:([a-z]+)(\\d+)", std::regex_constants::icase);
    std::cmatch cm;
    bool hit_c = std::regex_search(ctext, cm, re_c);
    int c_count = 0;
    for (std::cregex_iterator it(ctext, ctext + 19, re_c), end_it; it != end_it; ++it) {
        ++c_count;
    }
    std::string act2 = "hit=" + std::to_string(hit_s ? 1 : 0)
        + ";full=" + sm.str()
        + ";g1=" + sm[1].str()
        + ";g2=" + sm[2].str()
        + ";pos=" + std::to_string(sm.position(0))
        + ";sz=" + std::to_string(sm.size())
        + ";empty=" + std::to_string(sm.empty() ? 1 : 0)
        + ";cm=" + (hit_c ? cm[1].str() : "")
        + ";ccnt=" + std::to_string(c_count);
    std::string exp2 = "hit=1;full=user=Alice id=42;g1=Alice;g2=42;pos=0;sz=3;empty=0;cm=ab;ccnt=2";
    cases.push_back({
        "regex_search_and_smatch",
        lab::esc(exp2),
        lab::esc(act2),
        act2 == exp2
    });

    // Case 3: sregex_iterator and iterative regex_search
    std::string phones = "123-456-7890 and 987-654-3210";
    std::regex re_phone(R"(\d{3}-\d{3}-\d{4})");
    std::string found_phones;
    std::string cur = phones;
    std::smatch pm;
    while (std::regex_search(cur, pm, re_phone)) {
        if (!found_phones.empty()) found_phones += ",";
        found_phones += pm[0].str();
        cur = pm.suffix().str();
    }
    std::string mixed = "abc123def456";
    std::string iter_nums;
    for (std::sregex_iterator it(mixed.begin(), mixed.end(), re_digits), end_it; it != end_it; ++it) {
        if (!iter_nums.empty()) iter_nums += ",";
        iter_nums += it->str();
    }
    std::string act3 = "phones=" + found_phones + ";nums=" + iter_nums;
    std::string exp3 = "phones=123-456-7890,987-654-3210;nums=123,456";
    cases.push_back({
        "regex_iterator_all_matches",
        lab::esc(exp3),
        lab::esc(act3),
        act3 == exp3
    });

    // Case 4: regex_replace and match_flag_type::format_first_only
    std::string r1 = std::regex_replace(std::string("Hello, World!"), std::regex("World"), "Universe");
    std::string r2 = std::regex_replace(mixed, re_digits, "#");
    std::string r3 = std::regex_replace(mixed, re_digits, "#", std::regex_constants::format_first_only);
    std::string act4 = r1 + "|" + r2 + "|" + r3;
    std::string exp4 = "Hello, Universe!|abc#def#|abc#def456";
    cases.push_back({
        "regex_replace_and_flags",
        lab::esc(exp4),
        lab::esc(act4),
        act4 == exp4
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-libs-regex-lab/explore-cpp-libs-regex.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-regex.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2366.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习