首页 > 解决方案 > 使用正则表达式从另一个 c++ 文件中提取“标识符”

问题描述

我必须编写一个从另一个 C++ 文件中提取标识符的程序。通常,我在编写正则表达式时遇到问题,该表达式将提取这些“标识符”,这些“标识符”基本上是以任何字母(不区分大小写)或下划线开头的字符串。这是示例代码:

std::string line1 = "#include <iostream>";
std::string line2 = "int main() {";
std::string line3 = "   std::cout << \"Hello World!\";\n";
std::string line4 = "}";

我希望正则 rexpression 从此代码中提取以下子字符串: include、iostream、int、main、std、cout

到目前为止,我已经创建了一个正则表达式对象和一个变量匹配来存储匹配的子字符串:

std::smatch matches;
std::regex pattern("[a-zA-Z0-9_ ]+");

一般来说,我确实知道如何构建基于 OOP 的整个程序,只是使用了这个正则表达式。

这是我的函数,它从另一个逐行读取文件的类方法中获取行参数。

void IdentifierCounter::extract_identifiers(std::string line) {
std::regex reg("[\w]+");
if (regex_match(line, reg)) {
    std::cout << "Found a match!" << "\n";
}

}

整个代码:

#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <regex>
class IdentifierCounter {
public:
   std::string file_name;
   std::vector<std::string> vec_of_identifiers;
   std::map<std::string, int> identifiers;
   IdentifierCounter(std::string file_name);
   void extract_identifiers(std::string line);
};

IdentifierCounter::IdentifierCounter(std::string file_name) {
   std::ifstream file;
   std::string line;
   file.open(file_name);
   while (file) {
     getline(file, line);
     vec_of_identifiers.push_back(line);
}
file.close();
for (auto line : vec_of_identifiers) {
    extract_identifiers(line);
}
}

void IdentifierCounter::extract_identifiers(std::string line) {
std::regex reg("[\w]+");
if (regex_match(line, reg)) {
    std::cout << "Found a match!" << "\n";
}
}


int main()
{
IdentifierCounter obj1("Lab 11.cpp");
}

标签: c++regex

解决方案


推荐阅读