嗨,我希望得到以下表达式的值:
多边形(100 20,30 40,20 10,21 21)
搜索POLYGON(100 20,30 40,20 10,21 21)

当我执行以下代码时,我会得到以下结果:
 多边形(100 20,30 40,20 10,21 21)
 结果= 100 20
 r2 = 100
 r2 = 20
 r2 = 21 21
 r2 = 21
大小= 7

我不知道为什么我没有获得中间值...

感谢您的帮助

#include <iostream>
#include <boost/regex.hpp>

using namespace std;

void testMatch(const boost::regex &ex, const string st) {
 cout << "Matching " << st << endl;
 if (boost::regex_match(st, ex)) {
  cout << " matches" << endl;
 }
 else {
  cout << " doesn’t match" << endl;
 }
}

void testSearch(const boost::regex &ex, const string st) {
 cout << "Searching " << st << endl;
 string::const_iterator start, end;
 start = st.begin();
 end = st.end();
 boost::match_results<std::string::const_iterator> what;
 boost::match_flag_type flags = boost::match_default;
 while(boost::regex_search(start, end, what, ex, flags))
 {
  cout << " " << what.str() << endl;
  cout << " result = " << what[1] << endl;
  cout << " r2 = " << what[2] << endl;
cout << " r2 = " << what[3] << endl;
cout << " r2 = " << what[4] << endl;
cout << " r2 = " << what[5] << endl;
cout << "size = " << what.size() << endl;
  start = what[0].second;
 }
}

int main(int argc, char *argv[])
{
 static const boost::regex ex("POLYGON\\(((\\-?\\d+) (\\-?\\d+))(\\, (\\-?\\d+) (\\-?\\d+))*\\)");
 testSearch(ex, "POLYGON(1 2)");
 testSearch(ex, "POLYGON(-1 2, 3 4)");
 testSearch(ex, "POLYGON(100 20, 30 40, 20 10, 21 21)");
 return 0;
}

最佳答案

我不是正则表达式专家,但是我阅读了您的正则表达式,这似乎是正确的。

This forum post似乎在谈论完全相同的事情,Boost.Regex仅返回正则表达式的最后结果。显然,默认情况下,Boost仅跟踪重复比赛的最后一场比赛。但是,有一个实验功能可让您更改此设置。 More info here,在“重复捕获”下。

但是,还有其他两个“解决方案”:


使用正则表达式来跟踪第一对数字,然后删除该对子字符串并对该子字符串进行另一个正则表达式,直到获得所有输入。
使用Boost.Spirit,它可能比Boost.Regex更适合解析输入。

关于c++ - 带BoostRegex C++的正则表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5213852/

10-13 06:50