从文本文件中提取文件名

时间:2017-11-15 17:00:30

标签: c++ file istringstream

我需要将文件名及其扩展名从输入文本文件提取到字符串向量。 输入文本文件非常混乱,并作为某些应用程序的配置文件。

我对我要提取的文件名的了解是,它们之前是'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);
    }
}

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

1 个答案:

答案 0 :(得分:1)

从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;
}

这样,每次迭代你的行,都会得到文件名并打印出来,因为捕获组会捕获文件名。