简体   繁体   English

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

[英]Conditional replace string using boost::regex_replace

I want to simplify the signs in a mathematical expression using regex_replace, here is a sample code: 我想使用regex_replace简化数学表达式中的符号,这是示例代码:

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

The output is then 6?3?5. 输出为6?3?5。 My question is: How can I get the proper result of 6-3+5 with some neat regular expression tools? 我的问题是:如何使用一些整洁的正则表达式工具获得6-3 + 5的正确结果? Thanks a lot. 非常感谢。

Tried something else with sregex_iterator and smatch, but still has some problem: 使用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

It seems to me that the problem is related to the match.suffix(), Could anybody help please? 在我看来,问题与match.suffix()有关,有人可以帮忙吗? The collect_sign function basically just iterate through every sign strings, convert it to "-"/"+" if the number of "-" is odd/even, and then stitch together the suffix expression of the signs. 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;
}

Use: 采用:

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

Replace: 更换:

$1

You can test here 你可以在这里测试

If you just want a mathematical simplification, you can use: 如果只需要数学简化,可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM