Search code examples
c++regexboostgetline

C++ getline - Extracting a substring using regex


I have a file with contents like this -

Random text
+-------------------+------+-------+-----------+-------+
|     Data          |   A  |   B   |     C     |   D   |
+-------------------+------+-------+-----------+-------+
|   Data 1          | 1403 |     0 |      2520 | 55.67 |
|   Data 2          | 1365 |     2 |      2520 | 54.17 |
|   Data 3          |    1 |     3 |      1234 | 43.12 |
Some more random text

I want to extract the value of column D of row Data 1 i.e. I want to extract the value 55.67 from the example above. I am parsing this file line by line using getline -

while(getline(inputFile1,line)) {
    if(line.find("|  Data 1") != string::npos) {
        subString = //extract the desired value
}

How can I extract the desired sub string from the line. Is there any way using boost::regex that I can extract this substring?


Solution

  • While regex may have its uses, it's probably overkill for this.

    Bring in a trim function and:

    char delim;
    std::string line, data;
    int a, b, c;
    double d;
    
    while(std::getline(inputFile1, line)) {
        std::istringstream is(line);
        if( std::getline(is >> delim, data, '|') >>
            a >> delim >> b >> delim >> c >> delim >> d >> delim) 
        {
            trim(data);
    
            if(data == "Data 1") {
                std::cout << a << ' ' << b << ' ' << c << ' ' << d << '\n';
            }
        }
    }
    

    Demo