使用regex来帮助我使用计算器c++

using regex to help me on my calculator c++

本文关键字:计算器 c++ regex 帮助 使用      更新时间:2023-10-16

我正在做一个c++计算器,我正在使用正则表达式来生成语法。

但我很难验证表达式。

这是我的代码:

#include <regex>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main(){
    string blah;
    cout << "Expression :n";
    cin >> blah;
    regex numb("[-+]?[0-9]*\.?[0-9]+");
    regex ope("(\+|-|/|\*|\(|\))");
    regex exp("[-+]?[0-9]*\.?[0-9]+(\+|-|/|\*|\(|\))");
    smatch numbMatch;
    smatch opeMatch;
    smatch expMatch;

    if (!regex_search(blah, expMatch, exp)){
        cout << "Invalid expression" << endl;
        return main();
    }
    else{}
    do{
        if (regex_search(blah, numbMatch, numb)){
            for (unsigned int j = 0; j < numbMatch.size(); ++j)
                cout << "Number n" << numbMatch[j] << endl;
            blah = numbMatch.suffix().str();
        }
        if (regex_search(blah, opeMatch, ope)){
            for (unsigned int i = 1; i < opeMatch.size(); ++i){
                cout << "Operator n" << opeMatch[i] << endl;
                blah = opeMatch.prefix().str() + opeMatch.suffix().str();
            }
        }
    } while (true); {}
}

如果我把我的表情像a4+4一样,那就没用了。它通过了我的第一个正则表达式,但没有返回到main()

首先,递归函数通常是个坏主意。像这样的东西要好得多:

while (!regex_search(blah, expMatch, exp)){
        cout << "Invalid expression" << endl;
        cout << "Expression :n";
        cin >> blah;
}

无论如何,regex_search:

返回目标序列中的某个子序列(主题)匹配正则表达式rgx(模式)

字符串"a4+4"匹配,因为字符串中有表达式"4+4"。尝试使用如下正则表达式查找函数regex_match:

regex exp("[-+]?[0-9]*([-+*/][-+]?[0-9]+)*$");
while (!regex_match(blah, expMatch, exp)){
        cout << "Invalid expression" << endl;
        cout << "Expression :n";
        cin >> blah;
}

do..while循环也是一个无限循环。至少尝试:

} while (!blah.empty());