为什么我的c++正则表达式匹配正确,但没有返回正确的值

Why is my c++ regex matching correctly, but not returning the correct value?

本文关键字:返回 正则表达式 我的 为什么 c++      更新时间:2023-10-16

我有一个用于匹配多项式项的正则表达式,我将使用它来实现一个函数,将字符串转换为多项式类。您可以看到此处演示的正则表达式生成了正确的匹配项。然而,当我尝试实现它时,我的程序正确地找到了匹配项,但奇怪地将它们打印到屏幕上。例如:

-21323x^5+1233x4+123x^2-1232
Trying to match: -21323x^5+1233x4+123x^2-1232
-21323x^5
Trying to match: +1233x4+123x^2-1232
1233x4
Trying to match: +123x^2-1232
12xx^2
Trying to match: -1232
-1232

在这种情况下,由于某种原因,它打印12xx^2而不是123x^2

和另一个问题:

-1234x^5+789x4+6x^2-567+123x
Trying to match: -1234x^5+789x4+6x^2-567+123x
-1234x^5
Trying to match: +789x4+6x^2-567+123x
789x4
Trying to match: +6x^2-567+123x
x^22
Trying to match: -567+123x
-567
Trying to match: +123x
23xx

在本例中显示x^22而不是6x^2, 23xx而不是123x

这是我的代码:

Poly* Poly::fromString(std::string str) {
    Poly* re = new Poly;
    bool returnNull = true;
    std::regex r_term("((-?[0-9]*)x(\^?([0-9]+))?|-?[0-9]+)");
    std::smatch sm;
    while(std::regex_search(str, sm, r_term)) {
        returnNull = false;
        std::cout << "Trying to match: " << str << std::endl;
        str = sm.suffix().str();
        std::cout << sm.str() << std::endl;
    }
    if(returnNull) {
        delete re;
        return nullptr;
    } else return re;
}

虽然Igor正确地注意到当前代码的问题,但我认为您所需要的只是获得完整的模式匹配,为此目的,我宁愿建议使用regex迭代器:

std::regex r("(-?[0-9]*)x(\^?([0-9]+))?|-?[0-9]+");
std::string s = "-21323x^5+1233x4+123x^2-1232";
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
                         i != std::sregex_iterator();
                         ++i)
{
    std::smatch m = *i;
    std::cout << "Match value: " << m.str() << 'n';
    std::cout << "Group 1 value: " << m.str(1) << 'n';
    std::cout << "Group 2 value: " << m.str(2) << 'n';
    std::cout << "Group 3 value: " << m.str(3) << 'n';
}

查看c++在线演示

模式细节:

  • -? - 1或0连字符
  • [0-9]* - 0或更多数字
  • x -一个字面值字符x
  • (\^?([0-9]+))? - 1或0序列:
    • \^? -一个可选的(1或0)^符号
    • [0-9]+ - 1位或更多数字
  • | -或
  • -? -可选的连字符/减号
  • [0-9]+ - 1位或更多位。