扫码关注官方订阅号
A文件中,内容是这样的:
[fullText]abcd[rating] [fullText]efg[rating]
我想要抽取[fullText] [rating]之间的内容,并将其保存到B文件中, 不同标签对的内容用空格隔开。 应该怎么写呢?
[fullText] [rating]
走同样的路,发现不同的人生
用正则表达式就几行程序而已:
#include <iostream> #include <regex> int main() { std::regex r("\\[fullText\\](.*)\\[rating\\]"); std::string l; while(std::cin) { std::getline(std::cin, l); std::cout << std::regex_replace(l, r, "$1\n"); } }
如果你不纠结一定要用C++,那可以更短:
perl -pe 's/\[fullText\](.*)\[rating\]/$1/g'
逻辑很简单,知道一点字符串操作和文件操作就好。下面的代码可以实现你的要求,没有考虑异常处理,也没有过多考虑效率,需要的话你自己改改就好
#include <iostream> #include <fstream> #include <string> using namespace std; class Solution { public: int ProcessFile(const string &src_file, const string &dest_file, const string &head, const string &end) { ifstream input(src_file.c_str(), ifstream::in); if (!input) { return -1; } ofstream output(dest_file.c_str(), ofstream::out); if (!output) { return -1; } string line; string ::size_type head_len = head.length(); while(getline(input, line)) { string::size_type head_pos = line.find(head, 0); string::size_type end_pos = line.find(end, head_pos + head_len); output << line.substr(head_pos + head_len, end_pos - head_pos - head_len) << ' '; } input.close(); output.close(); return 0; } }; int main() { string src_file = "input.txt", dest_file = "output.txt"; string head_name = "[fullText]", end_name = "[rating]"; Solution sln; if (sln.ProcessFile(src_file, dest_file, head_name, end_name) < 0) { cout << "Fail..." << endl; } else { cout << "Success..." << endl; } return 0; }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
用正则表达式就几行程序而已:
如果你不纠结一定要用C++,那可以更短:
逻辑很简单,知道一点字符串操作和文件操作就好。下面的代码可以实现你的要求,没有考虑异常处理,也没有过多考虑效率,需要的话你自己改改就好