boost的正则表达式错误

Regex error with boost

本文关键字:错误 正则表达式 boost      更新时间:2023-10-16

我正在尝试匹配一个字符串,看起来像:

/new-contact?id=nb&name=test/new-contact?id=nb

基本上参数的数量是未定义的。

所以我尝试了这个正则表达式:

boost::regex re("^/new-contact\?(([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)&?)+$");

,但当我试图使用re与以下函数:

function test()
{
    std::string input("/new-contact?id=5&name=Test");
    boost:cmatch token;
    boost::regex_match(req.c_str(), token, input);
    std::cout << token[1] << std::endl;
}

我得到

output: name=Test

如果我把输入字符串改成

std::string input("/new-contact?id=5&");

output: id=5

我想我只得到最后一个令牌,但我应该得到最后一个"+"的一切?

我错过了什么?

现在使用:

^/new-contact\?((([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)&?)+)$

token[0]将包含整个匹配。随后的索引为您提供匹配的子标记,它们由表达式中的括号确定(括号组称为捕获组;对非捕获组使用(?:...))

在这里有说明。复制所提供的示例

#include <stdlib.h>
#include <boost/regex.hpp>
#include <string>
#include <iostream>
using namespace boost;
regex expression("([0-9]+)(\-| |$)(.*)");
// process_ftp: 
// on success returns the ftp response code, and fills 
// msg with the ftp response message. 
int process_ftp(const char* response, std::string* msg)
{
   cmatch what;
   if(regex_match(response, what, expression))
   {
      // what[0] contains the whole string 
      // what[1] contains the response code 
      // what[2] contains the separator character 
      // what[3] contains the text message. 
      if(msg)
         msg->assign(what[3].first, what[3].second);
      return std::atoi(what[1].first);
   }
   // failure did not match 
   if(msg)
      msg->erase();
   return -1;
}

我认为正则表达式是解析URL路径的错误工具。我可以推荐一个URL解析库吗?

您可以尝试使用延续转义G:

^/new-contact\?|(?>\G([^=]+)=([^&]+)&?)+