You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++读取文件用正则填充vector失败:无法进入regex_match分支求助

问题解决:正则匹配失败无法填充vector

我尝试读取文件内容并使用正则表达式填充vector,但程序无法进入if(regex_match(line,match,pattern))条件分支,请求协助解决。

input.txt内容

Name: Bhanu
RollNumber: 32
Discipline: ECE
Location: Hyderabad

Name: Raj
RollNumber: 92
Discipline: CSC
Location: Delhi

原代码

struct Student{
    string name;
    int rollnumber;
    string discipline;
    string location;
};
void readContentFromFile(vector<Studentst> &stuVect){
    ifstream inputFile("/home/bharath/input.txt");
    if(!inputFile.is_open()){cout<<"Could not open a File"<<endl; return;}
    else{
        string line;
        regex pattern("Name: [\\w+]\nRollNumber: [\\d+]\nDiscipline: [\\w+]\nLocation: [\\w+]");
        while(getline(inputFile,line)){
            smatch match;
            cout<<__LINE__<<" line: "<<line<<endl;

            if(regex_match(line,match,pattern))
            {
                cout<<__LINE__<<"Inside regex_match condition"<<endl;
                Student student;
                student.name = match[1].str();
                student.rollnumber = std::stoi(match[2].str());
                student.discipline = match[3].str();
                student.location = match[4].str();

            students.push_back(student);
            }
        }
    }
    cout<<endl<<endl<<endl;
    inputFile.close();
}


int main(){
    vector<Studentst> stuVector;
    readContentFromFile(stuVector);
    displayInfo(stuVector);
    return 0;
}

错误原因及修复方案

1. 逐行读取与正则匹配范围不匹配

getline(inputFile, line)每次只读取一行文本,但你的正则表达式是匹配4行连续内容的,单一行根本不可能满足正则条件,自然进不了分支。

解决:一次性读取整个文件内容,或者按学生条目(4行一组+空行)读取后再匹配。

2. 正则表达式写法错误

  • 原正则[\w+]是错误写法:[]是字符集,里面的+会被当作普通字符,正确应该用括号分组匹配多字符:(\w+)
  • 未设置捕获分组,导致match[1]、match[2]无法提取对应字段值
  • C++字符串中\需要转义,正则里的\w要写成\\w,用原始字符串字面量R"()"可避免转义

修正后的正则:

regex pattern(R"(Name: (\w+)\nRollNumber: (\d+)\nDiscipline: (\w+)\nLocation: (\w+))");

3. 变量名错误

  • vector<Studentst>应改为vector<Student>,结构体名为Student
  • students.push_back(student)应改为stuVect.push_back(student),函数参数是stuVect

4. 匹配方式问题

regex_match要求完全匹配输入字符串,读取整个文件后,需用regex_search循环查找所有匹配条目,或用迭代器遍历。

修复后的完整代码

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

using namespace std;

struct Student{
    string name;
    int rollnumber;
    string discipline;
    string location;
};

void displayInfo(const vector<Student>& stuVect) {
    for(const auto& stu : stuVect) {
        cout << "Name: " << stu.name << endl;
        cout << "RollNumber: " << stu.rollnumber << endl;
        cout << "Discipline: " << stu.discipline << endl;
        cout << "Location: " << stu.location << endl << endl;
    }
}

void readContentFromFile(vector<Student> &stuVect){
    ifstream inputFile("/home/bharath/input.txt");
    if(!inputFile.is_open()){
        cout << "Could not open a File" << endl; 
        return;
    }

    // 读取整个文件内容
    stringstream buffer;
    buffer << inputFile.rdbuf();
    string content = buffer.str();

    // 修正后的正则,用原始字符串避免转义,添加捕获分组
    regex pattern(R"(Name: (\w+)\nRollNumber: (\d+)\nDiscipline: (\w+)\nLocation: (\w+))");
    sregex_iterator it(content.begin(), content.end(), pattern);
    sregex_iterator end;

    for(; it != end; ++it) {
        smatch match = *it;
        Student student;
        student.name = match[1].str();
        student.rollnumber = stoi(match[2].str());
        student.discipline = match[3].str();
        student.location = match[4].str();
        stuVect.push_back(student);
    }

    inputFile.close();
}

int main(){
    vector<Student> stuVector;
    readContentFromFile(stuVector);
    displayInfo(stuVector);
    return 0;
}

代码说明

  1. 用stringstream读取整个文件,一次性处理所有学生条目
  2. 使用sregex_iterator遍历所有匹配项,自动跳过空行
  3. 正则添加捕获分组,正确提取每个字段值
  4. 修正所有变量名错误,补充displayInfo函数实现

内容的提问来源于stack exchange,提问作者BHARATH KUMAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:22:44