C++ 正则表达式提取文本中的 Windows 路径
使用 C++ 正则表达式提取文本中的 Windows 路径,可以使用以下代码示例:
#include <regex>
#include <iostream>
#include <string>
int main()
{
std::string input = 'This is a path: C:\Windows\system32\notepad.exe, and another path: D:\Documents\file.txt';
std::regex path_regex(R'(([A-Za-z]:\(?:[^<>:"/\|?*]+\)*[^<>:"/\|?*]+))');
std::sregex_iterator path_iterator(input.begin(), input.end(), path_regex);
std::sregex_iterator end_iterator;
while (path_iterator != end_iterator) {
std::cout << path_iterator->str() << std::endl;
++path_iterator;
}
return 0;
}
在这个例子中,我们使用了 C++11 中的正则表达式库 std::regex。首先定义了一个包含 Windows 路径的字符串,然后定义了一个正则表达式 path_regex 来匹配 Windows 路径。正则表达式的模式是 ([A-Za-z]:\(?:[^<>:"/\|?*]+\)*[^<>:"/\|?*]+),它匹配 Windows 路径的规则如下:
[A-Za-z]:匹配驱动器名称,例如 C:、D: 等。\(?:[^<>:"/\|?*]+\)*匹配路径中的目录名称,例如 Windows、system32 等。这里使用了非捕获组来避免捕获这些目录名称。[^<>:"/\|?*]+匹配文件名或扩展名,例如 notepad.exe、file.txt 等。
接下来,我们使用 std::sregex_iterator 来遍历所有匹配到的路径,并输出它们。
原文地址: https://www.cveoy.top/t/topic/oOiv 著作权归作者所有。请勿转载和采集!