使用boost :: regex_replace条件替换字符串

时间:2014-11-01 19:42:32

标签: c++ regex boost replace

我想使用regex_replace简化数学表达式中的符号,这是一个示例代码:

string entry="6+-3++5";
boost::regex signs("[\-\+]+");
cout<<boost::regex_replace(entry,signs,"?")<<endl;

输出为6?3?5。我的问题是:如何使用一些简洁的正则表达式工具获得6-3 + 5的正确结果?非常感谢。

使用sregex_iterator和smatch尝试了其他一些事情,但仍有一些问题:

string s="63--17--42+5555";
collect_sign(s);
Output is 
63+17--42+5555+42+5555+5555
i.e.
63+(17--42+5555)+(42+5555)+5555

在我看来,问题与match.suffix()有关,有人可以帮忙吗? collect_sign函数基本上只迭代每个符号字符串,如果“ - ”的数字是奇数/偶数,则将其转换为“ - ”/“+”,然后将符号的后缀表达式拼接在一起。

void collect_sign(string& entry)
{ 
    boost::regex signs("[\-\+]+");
    string output="";
    auto signs_begin = boost::sregex_iterator(entry.begin(), entry.end(), signs);
    auto signs_end = boost::sregex_iterator();
    for (boost::sregex_iterator it = signs_begin; it != signs_end; ++it) 
    {
        boost::smatch match = *it;
        if (it ==signs_begin)
            output+=match.prefix().str();
        string match_signs = match.str();
        int n_minus=count(match_signs.begin(),match_signs.end(),'-');
        if (n_minus%2==0)
            output+="+";
        else
            output+="-";
        output+=match.suffix();
    }
    cout<<"simplify to: "<<output<<endl;
}

2 个答案:

答案 0 :(得分:0)

使用:

[+\-*\/]*([+\-*\/])

替换:

$1

您可以测试here

答案 1 :(得分:0)

如果您只想进行数学简化,可以使用:

s = boost::regex_replace(s, boost::regex("(?:++|--"), "+", boost::format_all);
s = boost::regex_replace(s, boost::regex("(?:+-|-+"), "-", boost::format_all);