c++ - 使用正则表达式从另一个 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");
}
解决方案
推荐阅读
- swift - 如何在不丢失导航栏 UI 的情况下更改 SwiftUI 背景?
- c# - 如何在使用 C# 选择图像时获取图像地址或图像 URL
- google-apps-script - 在 appscript 中验证 google 电子表格 ID
- javascript - 如何从自定义占位符触发选择更改事件
- javascript - 仅使用 JavaScript 和 CSS 文本从左到右淡入淡出
- ios - 如何在表格视图的每个单元格下添加行?
- reactjs - 如何更新 ReactJS 中的上下文变量?
- sql - 查询以计算超过 24 小时间隔的时间总和
- visual-studio-code - 终端进程启动失败:启动过程中发生本机异常(无法启动终端进程:CreateProcess失败)
- javascript - TypeError:“编译”参数必须是编译的实例