使用 C++ 的 std::regexstd::regex_match 函数可以轻松提取文本中的 Windows 路径。以下是一个示例代码:

#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::string text = "This is a sample text. The path is C:\Program Files\Sample\File.txt. Another path is D:\My Documents\File.docx.";
    std::regex reg("([A-Za-z]:\\[^\\\/:*?'<>|
]*)");
    std::smatch match;

    while (std::regex_search(text, match, reg)) {
        std::cout << "Path found: " << match.str() << std::endl;
        text = match.suffix().str();
    }

    return 0;
}

该代码使用正则表达式 ([A-Za-z]:\\[^\\\/:*?'<>| ]*) 匹配 Windows 路径,然后使用 std::regex_search 函数在文本中查找所有路径。匹配的路径字符串将被打印到控制台。

解释:

  • ([A-Za-z]:\\[^\\\/:*?'<>| ]*) 正则表达式解释:
    • ([A-Za-z]:) 匹配字母盘符,例如 C:D:
    • \\ 匹配反斜杠 \
    • [^\\\/:*?'<>| ] 匹配除了反斜杠 \、冒号 :、星号 *、问号 ?、单引号 ' 、小于号 <、大于号 >、竖线 | 、回车符 和换行符 之外的所有字符。
    • * 表示匹配 0 个或多个前面的字符。
  • std::regex_search 函数在文本中查找匹配的路径,并将匹配结果存储在 match 变量中。
  • match.str() 获取匹配的字符串。
  • match.suffix().str() 获取匹配之后的文本,以便在循环中继续查找其他路径。

通过以上代码和解释,您可以轻松提取文本中的 Windows 路径,并使用 std::regexstd::regex_match 函数进行更复杂的文本处理。

C++ 正则表达式提取文本中的 Windows 路径

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

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