0

尝试针对借由 string stream 抽取成的 string 对象使用 regex_replace 时出错,求解。

 2 years ago
source link: https://www.v2ex.com/t/831119
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  C++

尝试针对借由 string stream 抽取成的 string 对象使用 regex_replace 时出错,求解。

  ShikiSuen · 1 天前 · 714 次点击

下文有三句 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.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK