【问题标题】:C++11 std::regex lookbehind alternativeC++11 std::regex 后视替代
【发布时间】: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


    【解决方案1】:

    您可以在这里使用非单词边界:

    std::regex exprZero{R"(\B\([^(),]+\))"};
    

    regex demo

    \B\([^(),]+\) 模式将匹配位于字符串开头或紧跟在非单词字符(字母、数字或 _ 之外的字符)之后的 ([^(),]+ 将消耗除(), 之外的1 个或多个字符,然后\) 将匹配) 字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-01
      • 2015-01-10
      • 2017-09-16
      • 2013-04-07
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2011-12-12
      相关资源
      最近更新 更多