【发布时间】:2019-10-26 20:15:05
【问题描述】:
我尝试在 C++11 中创建类来计算以 std::string 形式给出的数学公式。
std::string formula = "sqrt(3)+15*3*(2+3*4)+pow(2,3)+(2*(1+8))-(3*(1+pow(2,4)))";
我决定使用 std::regex 来搜索模式,获取它们,计算它们并用计算结果替换它们。为了计算这个公式,我做了 3 个模式。
std::regex exprOne{ "[a-zA-Z0-9]+\\([^(),]+\\)" };
std::regex exprTwo{ "[a-zA-Z0-9]+\\([^()]+\\)" };
std::regex exprZero{ "(?![a-z0-9])\\([^(),]+\\)" };
exprOne 匹配 sqrt(3)
exprTwo 匹配 pow(2,3) 和 pow(2,4)
但问题在于 exprZero 它需要匹配(2+3*4) 和(1+8),但它也匹配sqrt(3)。在互联网上我发现了lookbehind (?<![a-z0-9]),但std::regex 没有我在互联网上发现的lookbehind。有人建议使用 Boost.Regex,但我不想使用外部库。如果 std::regex 没有后视功能,您应该能够不使用它来做类似的事情吗?
exprZero 不应匹配 sqrt([^(),]+)、log([^(),]+)、log10([^(),]+) 等,但应匹配 ([^(),]+)。
这是 std::regex 中的一个模式吗?
【问题讨论】:
标签: c++ regex lookbehind