使用正则表达式拆分数学表达式

时间:2021-01-05 22:05:02

标签: c++ regex expression

我想使用正则表达式将以下数学表达式 -1+33+4.4+sin(3)-2-x^2 拆分为标记。我使用以下站点来测试我的正则表达式 link,这表明没有错。当我在 C++ 中实现正则表达式时,抛出以下错误 Invalid special open parenthesis 我寻找解决方案并找到以下 stackoverflow 站点 link 但它没有帮助我解决我的问题。 我的正则表达式代码是 (?<=[-+*\/^()])|(?=[-+*\/^()])。在 C++ 代码中,我不使用 \

另一个问题是我不知道如何确定减号是一元运算符还是二元运算符,如果减号是一元运算符我想看起来像这样{-1}

我希望令牌看起来像这样:{-1,+,33,+4.4,+,sin,(,3,),-,2,-,x,^,2}

一元减号可以在字符串中的任何位置。

如果我不使用 ^ 它仍然是错误的。

代码:

std::vector<std::string> split(const std::string& s, std::string rgx_str) {
      std::vector<std::string> elems;
      std::regex rgx (rgx_str);
      std::sregex_token_iterator iter(s.begin(), s.end(), rgx);
      std::sregex_token_iterator end;
      while (iter != end)  {
          elems.push_back(*iter);
          ++iter;
      }
      return elems;
}
int main() {
    std::string str = "-1+33+4.4+sin(3)-2-x^2";
    std::string reg = "(?<=[-+*/()^])|(?=[-+*/()^])";
    std::vector<std::string> s = split(str,reg);
    for(auto& a : s)
        cout << a << endl;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

C++ 默认使用 modified ECMAScript regular expression grammar 作为其 std::regex。它确实支持前瞻 (?=)(?!),但不支持后视。因此,(?<=) 不是有效的 std::regex 语法。

在 C++23 中添加了 a proposal,但目前尚未实现。