下文有三句 regex_replace 。
注释掉还好,不注掉的话会卡壳(且作为操作对象的文本档案会被清空)。所以我想来请教各位大佬。
(我一个月前刚开始自学编程,为了维护某个开源输入法专案。)
path 是某个有权限写入的纯文本 txt 档案的路径。
这段程式码主要用来做这几点(按顺序):
一、将所有 tab 与 全形空格 等 广义上的空格 都转成 半形英数空格。如果这些空格是连续的话,合并成一个空格。
二、抽掉行首与行尾的空格。
// FORMAT CONSOLIDATOR. CREDIT: Shiki Suen.
bool LMConsolidator::ConsolidateFormat(const char *path, bool hypy) {
ifstream zfdFormatConsolidatorIncomingStream(path);
stringstream zfdLoadedFileStreamToConsolidateBuff; // 設立字串流。
ofstream zfdFormatConsolidatorOutput(path); // 這裡是要從頭開始重寫檔案內容,所以不需要「 ios_base::app 」。
zfdLoadedFileStreamToConsolidateBuff << zfdFormatConsolidatorIncomingStream.rdbuf();
string zfdBuffer = zfdLoadedFileStreamToConsolidateBuff.str();
// 下面這幾句用來執行非常複雜的 Regex 取代。
regex sedWhiteSpace("\\h+"), sedLeadingSpace("^ "), sedTrailingSpace(" $");
zfdBuffer = regex_replace(zfdBuffer, sedWhiteSpace, " ").c_str();
zfdBuffer = regex_replace(zfdBuffer, sedLeadingSpace, "").c_str();
zfdBuffer = regex_replace(zfdBuffer, sedTrailingSpace, "").c_str();
// 漢語拼音二式轉注音。
if (hypy) {
// 該功能尚未正式引入。
}
// 最終將取代結果寫入檔案。
zfdFormatConsolidatorOutput << zfdBuffer << std::endl;
zfdFormatConsolidatorOutput.close();
if (zfdFormatConsolidatorOutput.fail()) {
syslog(LOG_CONS, "// REPORT: Failed to write format-consolidated data to the file. Insufficient Privileges?\n");
syslog(LOG_CONS, "// DATA FILE: %s", path);
return false;
}
zfdFormatConsolidatorIncomingStream.close();
if (zfdFormatConsolidatorIncomingStream.fail()) {
syslog(LOG_CONS, "// REPORT: Failed to read lines through the data file for format-consolidation. Insufficient Privileges?\n");
syslog(LOG_CONS, "// DATA FILE: %s", path);
return false;
}
return true;
} // END: FORMAT CONSOLIDATOR.
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.