C ++ std :: regex。通过正则表达式搜索子字符串时出错

时间:2014-12-24 08:27:19

标签: c++ regex visual-studio-2012 c++11

更新:实际上已经删除了所有不必要的代码。

我正在使用Visual Studio Express 2012。

我编写了函数,通过常规expressin搜索字符串中的子串,并用索引(i1,i2,i16 ......)替换它。它工作得很好,但是在这里不再匹配字符串中的子串,我得到错误:

  

Expression:string iterator not dereferencable

我这样匹配:

std::smatch m;
std::regex rExp("[a-z][a-z0-9]*");
strBuf = "*10.5)*51E-10";
while (std::regex_search (strBuf, m, rExp)) {...

在main()中它工作正常,但是当它出现功能错误消息时会弹出。

完整代码:

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <regex>
    #include <fstream>

    std::string IntToString(int a) {
       std::string result;
       int number = abs(a);
       while (number) {
          result += (number % 10) + 48;
          number /= 10;
       }
       if (a < 0) result += '-';
       std::reverse(result.begin(), result.end());
       return result;
    }

    void searchLexemes(std::string& input, int& i)
    {
            std::string strBuf;
            std::smatch m;
            std::regex rExp("[a-z][a-z0-9]*");
            strBuf = input;
            input = "";
            bool foundAny = false;
            while (std::regex_search (strBuf, m, rExp)) { //here error happens
                    auto x = m.str();
                    input += m.prefix();
                    input += "i" + IntToString(i);
                    strBuf = m.suffix();
                    foundAny = true;
                    i++;
            }
            foundAny ? input += m.suffix() : input = strBuf;
    }

    void main() {
            std::string input;
            input = "fgs1=(b+a*5.01E+10)+a*10+(c*10.5)*51E-10";

            std::ofstream fout;
            fout.open("OUTPUT.TXT");

            int i = 1;

            searchLexemes(input, i);

            std::cout << input << std::endl;
            //expected result - "i1=(i2+i3*i5)+i3*i8+(i4*i7)*i6"

            system ("pause");
    }

0 个答案:

没有答案