首页 > 解决方案 > 捕获组标准 C++ RegEx 和 PCRE 中只有 1 个匹配项

问题描述

我有一个似乎无法解决的大问题,我正在尝试解析由 C++ 中的 uWebSockets 检索到的表单数据。我决定为此使用 RegEx。在尝试使用 C++ 标准函数后,它根本不起作用,运行大约需要 5 分钟。在尝试在其他语言(https://regex101.com/r/qbPupp/1)上运行 RegEx 之后,在我看来问题在于 C++(或 JavaScript)不允许在捕获组中回溯,因为它可以工作其他任何语言都可以。切换到 PCRE 允许进行 1 次匹配(并且检索结果的速度提高了大约 10 倍),但其余的仍然是空的。您可以在我在上面或此处发送的链接中看到 PCRE(v2 和 v1)按预期工作:https ://regexr.com/5sb7a 。

这是一个很好地描述问题的例子:

#include <pcrecpp.h>
#include <iostream>

int main() {
    std::string contents = "--------------------------eba4d02620bdb4f6\nContent-Disposition: form-data; name=\"ZIP\"; filename=\"h.png\"\nContent-Type: image/png\n\n--------------------------8c078fed966ff6fe\nContent-Disposition: form-data; name=\"ZIP\"; filename=\"tree-pack.xml\"\nContent-Type: application/xml\n\n<?xml version=\"1.0\"?>\n<Packages>\n  <Individual name=\"Designer\">\n    <Name>Designer</Name>\n    <Description>A BrAIn-API add-on that adds routes to help people design. This makes routes to generate colour palettes, generates fonts and even send previews of those to show how they look.</Description>\n    <ID></ID>\n    <FilePath>/packages/ID</FilePath>\n  </Individual>\n</Packages>\n\n--------------------------8c078fed966ff6fe--\n\n--------------------------eba4d02620bdb4f6--\n";
    pcrecpp::RE reg("-+.+\\nContent-Disposition: form-data; name=\"(\\w+| +)\"; filename=\"(.+)\"\\nContent-Type: (\\w+\\/\\w+)\\n\\n((.|\\n)+)\\n-+.+--.+|\\n+", pcrecpp::RE_Options()
    .set_caseless(true)
    .set_multiline(true));
    pcrecpp::StringPiece input(contents);
    int count = 0;
    std::string match;

    std::cout << contents << std::endl;

    while (reg.FindAndConsume(&input, &match)) { //This while loop makes sure that it only logs the amount of matches it is able to find; giving it a defined amount of matches it needs to find has the same output.
        count++;
        std::cout << count << " " << match << std::endl;
    }
}

我在 Ubuntu 20.04 上运行它g++ file.cpp -o file -lpcrecpp。我的输出是:

Content-Disposition: form-data; name="ZIP"; filename="h.png"
Content-Type: image/png

--------------------------8c078fed966ff6fe
Content-Disposition: form-data; name="ZIP"; filename="tree-pack.xml"
Content-Type: application/xml

<?xml version="1.0"?>
<Packages>
  <Individual name="Designer">
    <Name>Designer</Name>
    <Description>A BrAIn-API add-on that adds routes to help people design. This makes routes to generate colour palettes, generates fonts and even send previews of those to show how they look.</Description>
    <ID></ID>
    <FilePath>/packages/ID</FilePath>
  </Individual>
</Packages>

--------------------------8c078fed966ff6fe--

--------------------------eba4d02620bdb4f6--

1 ZIP
2 

如果您对已经解析 formdata 或任何内容的库有任何建议,我也很想听听。

感谢您的阅读,并提前感谢我能得到的任何和所有帮助!

标签: c++regexpcre

解决方案


推荐阅读