c++ - 从文本文件中提取文件名

标签 c++ file istringstream

我需要将文件名及其扩展名从输入文本文件提取到字符串 vector 。 输入的文本文件非常困惑,用作某些应用程序的配置文件。

我所知道的关于我试图提取的文件名是它们前面有一个 'file =' 提及,文件名在 ' ' 或 ""之间被引用。示例:file="name.abc"。我也不能保证间距是多少:它可能是 file="name.abc", file = "name.abc", file= "name.abc"... 并且扩展名可以有不同的长度。

所以我尝试了下面的代码:

std::vector<std::string> attachment_names;
std::istringstream words(text_content);
std::string word;
std::string pst_extension(".abc"); // My code should support any extension
while (words >> word)
{
    auto extension_found = word.find(abc_extension);
    if (extension_found != word.npos)
    {
        auto name_start = word.find("'") + 1; 
             //I am not even sure the file is quoted by ''

        std::string attachment_name = word.substr(name_start, (extension_found + 3) - name_start + 1); 
             //Doing this annoys me a bit... Especially that the extension may be longer than 3 characters

        attachment_names.push_back(attachment_name);
    }
}

有更好的方法吗?是否有可能更多地依赖文件标题来支持任何扩展?

最佳答案

从 C++11 或使用 boost,我的建议是你 对这个问题使用带有正则表达式迭代器的正则表达式,因为空格的数量有变化并且解析会变得有点困惑。 sregex_iterator 将遍历文本并匹配正则表达式(您可以使用任何双向迭代器作为源,例如,使用 getline 获取的字符串)。一个未经测试的想法如下:

static std::regex const filename_re("[[:space:]]*file[[:space:]]*=(.*)[[:space:]]*");

std::regex_iterator rit(line.begin(), line.end(), filename_re), end;


while (rit != end) {
  cout << rit[1] << ',';
  ++rit;
}

这对每次迭代都采用你的行,将找到找到的文件名并将其打印出来,因为捕获组捕获了文件名。

关于c++ - 从文本文件中提取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47313213/

相关文章:

c++ - 在使用不同的 visual studio 编译器版本编译的进程中加载​​ COM

c++ - 在 map 中已知值时获取键的最佳方法

c++ - STL 与 struct 的速度问题

c++ - 将输入输入到 vector<int> 的优雅解决方案

C++ 指向函数的指针作为参数。数据类型不兼容

c++ - 在文本文件中间附加字符串

无法将正确的文件目录输出到带有 .cFileName 的链接列表

c - read() 调用后 Printf 打印垃圾。偏移量始终打印为 0

C++ 将 ifstream 管道化为 stringstream

C++ istringstream 和空格