以下是用C++11正则表达式提取window路径的示例代码:

#include <regex>
#include <iostream>

int main() {
    std::string text = "wTitle = 地址: D:\\Work\\gst\\文档\\脚本";
    std::regex pattern(R"((\w:|\\\\[\w-]+\\[\w.$]+)\\([\w-]+\\)*([\w-]+\.)*\w+)");
    std::smatch match;

    if (std::regex_search(text, match, pattern)) {
        std::string path = match.str();
        // 转换为char*
        char* cstr = new char[path.length() + 1];
        std::strcpy(cstr, path.c_str());
        std::cout << cstr << std::endl;
        delete[] cstr;
    }

    return 0;
}

代码解释:

  1. 使用std::regex定义正则表达式模式,该模式匹配window路径。

  2. 使用std::smatch存储匹配结果。

  3. 使用std::regex_search在文本中查找匹配。

  4. 如果有匹配结果,从std::smatch中获取路径字符串。

  5. 使用new和delete[]手动分配和释放内存,将路径字符串转换为char*类型。

  6. 打印路径字符串。

注意:正则表达式模式中使用了原始字符串字面量(Raw String Literal)R"()",以避免反斜杠字符被转义

C++正则提取文本里面的window路径文本wTitle = 地址 DWorkgst文档脚本结果用char保存vc11

原文地址: https://www.cveoy.top/t/topic/hlDN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录