在使用正则表达式执行函数时逐行解析inFile

时间:2016-10-28 20:15:48

标签: c++ regex iterator ifstream ofstream

我在角落里画自己,需要一些指导。我在从infstream读取时使用正则表达式进行一些解析。我想做的是

while(getLine(inFile, str)) {

     search(str) for regex match
     if(match)
         str = my_function(str)
         outFile << str
     else 
         outFile unchanged str
}

目前,我正在这样做:

while(getLine(inFile, str)) {

 auto des = std::sregex_iterator(str.cbegin(), str.cend(), dest);
 auto reg_it = std::sregex_iterator();

 std::for_each(des , reg_it, [](std::smatch const& m){
          str = my_function(str)
          outFile << str
        });
}

不幸的是,这不允许我编辑文件并按按顺序将其写回,因为我这样做的方式只能让我访问返回的匹配项。

任何指导都将不胜感激!

2 个答案:

答案 0 :(得分:1)

这有效:

if (std::regex_match(str.cbegin(), str.cend(), matches , my_regex)) {
        string baz;
        baz = my_function(str); // we have a match
        outFile baz;
}
else outFile << str << std::endl;

答案 1 :(得分:0)

这会有用吗?

while(getLine(inFile, str)) {

    auto des = std::sregex_iterator(str.cbegin(), str.cend(), dest);
    auto reg_it = std::sregex_iterator();
    int matches = 0;

    std::for_each(des , reg_it, [](std::smatch const& m)){
        str = my_function(str);
        outFile << str;
        matches++;
    });

    if (matches == 0) {
        outFile << str;
    }
}