c++ - 使用 BoostRegex C++ 的正则表达式

标签 c++ regex boost boost-regex

您好,我想获取以下表达式的值: 多边形(100 20、30 40、20 10、21 21) 搜索多边形(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 ,在“重复捕获”下。

不过还有 2 个其他“解决方案”:

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

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

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

相关文章:

构造函数中的 C++ 链接器错误

html - 正则表达式删除 HTML 中的 <font> 标签

c++ - 创建没有可调用对象的 boost::thread

c++ - 将成员函数添加到 Boost.Variant

c++ - 如何为涉及对象成员、间接和强制转换的排序算法实现 lambda 函数?

c++ - 如何忽略前 50 秒的信号?

c++ - 运行时功能测试、setjmp、longjmp 和信号掩码

java - 方法参数的@Pattern注解

C++ 无法翻转 ppm 图像

php - 以特定字符串开头和结尾且中间没有(其他)字符串的正则表达式