为什么我的c++正则表达式匹配正确,但没有返回正确的值
Why is my c++ regex matching correctly, but not returning the correct value?
我有一个用于匹配多项式项的正则表达式,我将使用它来实现一个函数,将字符串转换为多项式类。您可以看到此处演示的正则表达式生成了正确的匹配项。然而,当我尝试实现它时,我的程序正确地找到了匹配项,但奇怪地将它们打印到屏幕上。例如:
-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位或更多位。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- 正则表达式库,用于维护状态,逐个字符接受输入,并在找到匹配时返回true
- 为什么我的c++正则表达式匹配正确,但没有返回正确的值