Home > Blockchain >  My code with regular expressions for file doesn't run properly
My code with regular expressions for file doesn't run properly

Time:12-15

#include <iostream>
#include <fstream>
#include <string>
#include <regex>

using namespace std;
int main()
{

    regex r1("(.*\\blecture\\b.*)");
    regex r2("(.* practice.*)");
    regex r3("(.* laboratory practice.*)");
    smatch base_match;
    int lecture = 0;
    int prakt = 0;
    int lab = 0;
    string name = "schedule.txt";
    ifstream fin;
    fin.open(name);
    if (!fin.is_open()) {
        cout << "didint open ";
    }
    else {
        string str;
        while (!fin.eof()) {
            str = "";
            getline(fin, str);
            cout << str << endl;

            if (regex_match(str, base_match, r1)) {
                lecture  ;
            }
            if (regex_match(str, base_match, r2)) {
                prakt  ;
            }
            if (regex_match(str, base_match, r3)) {
                lab  ;
            }
        }
    }
    cout << "The number of lectures: " << lecture << "\n";
    cout << "The number of practices: " << prakt << "\n";
    cout << "[The number of laboratory work][1]: " << lab << "\n";

    fin.close();
}

In this program, I need to count the number of lectures, practice and laboratory work per week using regular expressions. I have got a text file, which you can see on the screen. But for lectures and practice, it doesn't work right.

enter image description here

CodePudding user response:

You need the number of times each regex matches. C has std::sregex_iterator for performing multiple regex matches over a string. That means you can do the following:

for (auto it = std::sregex_iterator{str.cbegin(), str.cend(), r1}; it != std::sregex_iterator{}; it  ) {
  lecture  ;
}

If you want to get really fancy you can even do it in one go:

auto it = std::sregex_iterator{str.cbegin(), str.cend(), r1};
lecture  = std::distance(it, std::sregex_iterator{});

Alternatively, you can call std::regex_search several times, starting from the end offset of the previous match (or 0 for the first).

EDIT: as remarked in the comments, this assumes that your regexes are suitable to incremental matching. Yours eat the whole string (presumably because regex_match is anchored whereas regex_search/regex_iterator are not), so you need to at least change your regular expression definitions to the following:

regex r1("\\blecture\\b");
regex r2(" practice");
regex r3(" laboratory practice");

... and of course every match for r3 is also a match for r2, but I leave that for you.

  •  Tags:  
  • c
  • Related