0

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

当我执行以下代码时,我得到了这个结果:
POLYGON(100 20, 30 40, 20 10, 21 21)
result = 100 20
r2 = 100
r2 = 20
r2 = , 21 21
r2 = 21
size = 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;
}
4

2 回答 2

2

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

这个论坛帖子似乎在谈论完全相同的事情,其中​​ Boost.Regex 只返回正则表达式的最后一个结果。显然,默认情况下,Boost 只跟踪重复匹配的最后一个匹配。但是,有一个实验性功能可让您更改此设置。更多信息在这里,在“重复捕获”下。

不过还有另外两个“解决方案”:

  1. 使用正则表达式跟踪第一对数字,然后获取删除该对的子字符串并对该子字符串执行另一个正则表达式,直到您获得所有输入。

  2. 使用Boost.Spirit,它可能比 Boost.Regex 更适合解析输入。

于 2011-03-06T23:19:23.577 回答
0

我从 IRC 频道得到了结果。正则表达式是:

static const boost::regex ex("[\\d\\s]+");
static const boost::regex ex("[\\-\\d\\s]+");
于 2011-03-06T23:20:14.990 回答