首页 > 解决方案 > 从已知大小和一些索引字符的文件中搜索字符串

问题描述

我想从匹配某些条件的文件中查找字符串。我知道字符串的大小和一些位置字符。因此,据我所知,最好的解决方案是创建正则表达式并搜索文件中的字符串。

我创建了以下正则表达式来搜索所有可能的字符:

[a-zA-Z0-9#&()\.\-/=?%@!\^\$\\ \.\*\+\?\(\)\[\]\{\}\|]

在我使用上述正则表达式编写的代码下方:

int main()
{
    std::ifstream t("file.txt");
    std::string str((std::istreambuf_iterator<char(t)),std::istreambuf_iterator<char>());

    smatch m;
    string allchar = "[a-zA-Z0-9#&()\.\-/=?%@!\^\$\\ \.\*\+\?\(\)\[\]\{\}\|]";

    //String of size five, have S at 0th index and B at last index
    string search = "S"+ allchar + allchar + allchar +"B";

    regex r(search);
    regex_search(str, m, r);

    for (auto x : m)
    {
        cout << x << endl;
    }
}

但是使用上面的代码我没有得到我应该得到的正确答案。我认为我在创建全字符字符串时犯了一些错误,但无法识别我的错误。

标签: c++regex

解决方案


推荐阅读