文件 A 內容格式:
[fullText]abcd[rating]
[fullText]efg[rating]
提取 [fullText] 和 [rating] 之間的內容,保存到文件 B,不同標簽對內容用空格分隔。
<regex> 正則提取#include
#include
#include
#include
#include
int main() {
std::ifstream in("A.txt");
std::ofstream out("B.txt");
std::string content((std::istreambuf_iterator(in)), std::istreambuf_iterator());
// 正則:\[fullText\](.*?)\[rating\] 非貪婪匹配
std::regex pattern(R"(\[fullText\](.*?)\[rating\])");
std::smatch match;
std::vector results;
std::string::const_iterator start = content.cbegin();
while (std::regex_search(start, content.cend(), match, pattern)) {
results.push_back(match[1].str()); // 第 1 捕獲組
start = match.suffix().first;
}
for (size_t i = 0; i < results.size(); ++i) {
out << results[i];
if (i + 1 < results.size()) out << ' ';
}
return 0;
}
R\"(...)\" 避免轉義混亂。.*? 非貪婪匹配,確保提取最近的 [rating]。match[1] 為第一個捕獲組(括號內內容)。re.findall 生成中間文件,C++ 僅讀取結果。