在行尾之前查找最后一个值

Finding last value before end of line

我正在开发一个程序,该程序可以解析标签并通过转义码更改控制台中文本的颜色。输入从 cin 中逐行读取,当读取 <> 中的标记时,它会根据我制作的映射进行检查以确定有效的转义码。

我的输出使用以下输出传送到标准输出:

cout << m.prefix() << getFromMap(tagMap, stack.back());

我的问题是,除非我有偶数个代码,否则我无法打印所有输入,因为最后一个输入在 smatch m.suffix()

我用来解析正则表达式行的循环是

for (auto it = uline.cbegin(), end = uline.cend(); regex_search(it, end, m, tag); it = m.suffix().first)

现在我需要设计一个 if 语句,在下一个 == uline.cend() 时触发 这样我就可以

cout<<m.suffix();

相关性的完整循环转储:

while (getline(cin, uline)) {
    //Check line for tags
    for (auto it = uline.cbegin(), end = uline.cend(); regex_search(it, end, m, tag); it = m.suffix().first) {

        ctag = m.str(1);

        //if closing tag
        if (ctag[0] == '/') {
            //Error for closing <text> early
            if (ctag == "/text" && stack.size() > 1) {
                cerr << getFromMap(tagMap, "text") << "ERROR on line " << count << " unclosed tags before</text>" << endl;
                return -1;
            }
            //check current tag against back if yes alter stack
            if (ctag.substr(1) == stack.back() && stack.size() > 0) {
                stack.pop_back();
            }
            //if not tags are improperly nested throw error
            else {
                cerr << getFromMap(tagMap, "text") << "ERROR on line " << count << " improperly nested tags" << endl;
            }
        }
        //if opening tag.
        else {
            //Failure to find tag in map
            if (!(findInMap(tagMap, m[1]))) {
                cerr << getFromMap(tagMap, "text") << "ERROR on line " << count << " tag not found in map" << endl;
                return -1;
            }
            //Check for bad input 
            if (first) {
                //Check for <text> being first tag
                if (m[1] != "text") {
                    cerr << getFromMap(tagMap, "text") << "ERROR on line " << count << " first tag not <text>" << endl;
                    return -1;
                }
                //Check for input before <text> 
                if (!m.prefix().str().empty() && !checkEmpty(m.prefix().str()))
                {
                    cerr << getFromMap(tagMap, "text") << "ERROR on line " << count << " text precedes <text> tag" << endl;
                    return -1;
                }
            }
            //add to stack if all tests passed
            stack.push_back(m[1]);
            first = false;
        }
        //should output here
        cout << m.prefix() << getFromMap(tagMap, stack.back());
    }

    cout << endl;
    count++;
}

您似乎需要将整个输入视为单个文档,因为开始和结束标记可能位于不同的行上。一种简单的方法是在输入流上而不是在每一行上使用迭代器:

for (auto it = istream_iterator<char>(cin), end = istream_iterator<char>();
    regex_search(it, end, m, tag); it = m.suffix().first) {
    // ...