【发布时间】:2010-11-15 04:22:04
【问题描述】:
我正在编写一个小型命令行程序,它以 ax^2+bx^1+cx^0 的形式向用户询问多项式。我稍后会解析数据,但现在我只是想看看我是否可以将多项式与正则表达式匹配(\+|-|^)(\d*)x\^([0-9*]*)我的问题是,它不匹配用户输入的多项式中的多个项,除非我将其更改为((\+|-|^)(\d*)x\^([0-9*]*))*(不同之处在于整个表达式被分组并在末尾有一个星号)。如果我输入诸如“4x^2”而不是“4x^2+3x^1+2x^0”之类的内容,则第一个表达式有效,因为它不会检查多次。
我的问题是,为什么 Boost.Regex'sregex_match()在同一个字符串中找不到多个匹配项?它在我使用的正则表达式编辑器(Expresso)中,但在实际的 C++ 代码中没有。应该是这样的吗?
如果有什么不合理的地方,请告诉我,我会尽力澄清。感谢您的帮助。
Edit1:这是我的代码(我正在学习这里的教程:http://onlamp.com/pub/a/onlamp/2006/04/06/boostregex.html?page=3)
int main()
{
string polynomial;
cmatch matches; // matches
regex re("((\\+|-|^)(\\d*)x\\^([0-9*]*))*");
cout << "Please enter your polynomials in the form ax^2+bx^1+cx^0." << endl;
cout << "Polynomial:";
getline(cin, polynomial);
if(regex_match(polynomial.c_str(), matches, re))
{
for(int i = 0; i < matches.size(); i++)
{
string match(matches[i].first, matches[i].second);
cout << "\tmatches[" << i << "] = " << match << endl;
}
}
system("PAUSE");
return 0;
}
【问题讨论】: