【发布时间】:2015-02-01 21:37:48
【问题描述】:
我正在使用正则表达式来分隔 HTTP 请求的字段:
GET /index.asp?param1=hello¶m2=128 HTTP/1.1
这边:
smatch m;
try
{
regex re1("(GET|POST) (.+) HTTP");
regex_search(query, m, re1);
}
catch (regex_error e)
{
printf("Regex 1 Error: %d\n", e.code());
}
string method = m[1];
string path = m[2];
try
{
regex re2("/(.+)?\\?(.+)?");
if (regex_search(path, m, re2))
{
document = m[1];
querystring = m[2];
}
}
catch (regex_error e)
{
printf("Regex 2 Error: %d\n", e.code());
}
不幸的是,此代码在 MSVC 中有效,但不适用于 GCC 4.8.2(我在 Ubuntu Server 14.04 上拥有)。您能否建议一种使用普通 std::string 运算符拆分该字符串的不同方法?
由于查询字符串分隔符“?”,我不知道如何将 URL 拆分为不同的元素。字符串中可能出现也可能不出现。
【问题讨论】:
-
您可以考虑使用 boost 正则表达式库 (boost.org/doc/libs/1_57_0/libs/regex/doc/html/index.html)
-
请提供更多信息。如果(您提到的)查询字符串分隔符丢失,您的代码将无法工作。那么两个平台上的输入是什么? @Christophe:总是指向 boost 可能并不总是一个好的提示。
-
@St0fF 对不起,但他的代码可以工作:我将它剪切并粘贴到 MSVC2013 并得到了预期的结果(method="GET", document="index.asp", queerrystring="param1=你好¶m2=128")
-
@MarkMiles 你能告诉我们什么不起作用吗?我在 ideone (ideone.com/QZqQM1) 上测试了您的代码,它还返回了正确的结果(使用 gcc 4.9.2)
-
正如我在帖子中所写:“不幸的是,此代码在 MSVC 中有效,但不适用于 GCC 4.8.2”。它必须在 Ubuntu 14.04 上运行。如果我这样做
#gcc --version它说它是 4.8.2 但如果我这样做apt search gcc-4.9我得到gcc-4.9-base/trusty,now 4.9-20140406-0ubuntu1 armhf [installed] GCC, the GNU Compiler Collection (base package)所以我不知道如何更新我的 gcc。
标签: c++ string parsing httprequest