C++正则提取文本里面的window路径文本wTitle = 地址 DWorkgst文档脚本和wTitle = 地址 D结果用char保存vc11
以下是使用C++11标准库的代码示例:
#include <iostream>
#include <regex>
#include <string>
int main()
{
std::string text = "wTitle = 地址: D:\\Work\\gst\\文档\\脚本";
std::regex pattern(R"(wTitle = 地址: (D:\\(?:[^\\]+\\)*))");
std::smatch match;
if (std::regex_search(text, match, pattern))
{
std::string path = match[1];
std::cout << path << std::endl;
// Convert to char*
const char* c_path = path.c_str();
std::cout << c_path << std::endl;
}
return 0;
}
输出结果:
D:\Work\gst\文档\
D:\Work\gst\文档\
代码解释:
- 定义字符串变量
text,存储待匹配的文本。 - 定义正则表达式
pattern,使用原始字符串字面量(R"()),其中\\表示转义字符\。 - 定义
std::smatch类型的变量match,用于存储匹配结果。 - 使用
std::regex_search()函数进行正则匹配,如果匹配成功,match[1]存储的是路径字符串。 - 将
std::string类型的路径字符串转换为const char*类型的C风格字符串,使用std::string::c_str()函数。 - 输出结果
原文地址: http://www.cveoy.top/t/topic/hlI5 著作权归作者所有。请勿转载和采集!