c++ - 需要帮助构建正则表达式模式

标签 c++ regex

我未能为 STL regex_match 函数创建模式,需要一些帮助来理解为什么我创建的模式不起作用以及如何修复它。 我认为正则表达式会对 dl.boxcloud.com 产生影响,但事实并非如此。

****仍在寻找意见。我更新了程序反射(reflect)建议。当我认为应该是一场比赛时,却有两场比赛。

#include <string>
#include <regex>
using namespace std;

wstring GetBody();
int _tmain(int argc, _TCHAR* argv[])
{
    wsmatch m;
    wstring regex(L"(dl\\.boxcloud\\.com|api-content\\.dropbox\\.com)");
    regex_search(GetBody(), m, wregex(regex));
    printf("%d matches.\n", m.size());

    return 0;
}
wstring GetBody() {
    wstring body(L"ABOUTLinkedIn\r\n\r\nwall of textdl.boxcloud.com/this/file/bitbyte.zip sent you a message.\r\n\r\nDate: 12/04/2012\r\n\r\nSubject: RE: Reference Ask\r\n\r\nOn 12/03/12 2:02 PM, wall of text wrote:\r\n--------------------\r\nRuba,\r\n\r\nI am looking for a n.");
    return body;
}

最佳答案

代码本身没有问题。您将 m.size() 误认为是匹配项的数量,而实际上,它是您的正则表达式返回的的数量。

std::match_results::size reference不利于理解:

Returns the number of matches and sub-matches in the match_results object.

总共有 2 个组(因为您围绕 2 个备选方案定义了一个捕获组)和 1 个匹配项。

参见 this IDEONE demo

#include <regex>
#include <string>
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    string data("ABOUTLinkedIn\r\n\r\nwall of textdl.boxcloud.com/this/file/bitbyte.zip sent you a message.\r\n\r\nDate: 12/04/2012\r\n\r\nSubject: RE: Reference Ask\r\n\r\nOn 12/03/12 2:02 PM, wall of text wrote:\r\n--------------------\r\nRuba,\r\n\r\nI am looking for a n.");
    std::regex pattern("(dl\\.boxcloud\\.com|api-content\\.dropbox\\.com)");
    std::smatch result;

    while (regex_search(data, result, pattern)) {
        std::cout << "Match: " << result[0] << std::endl;
        std::cout << "Captured text 1: " << result[1] << std::endl;
        std::cout << "Size: " << result.size() << std::endl;
        data = result.suffix().str();
    }
}

输出:

Match: dl.boxcloud.com
Captured text 1: dl.boxcloud.com
Size: 2

看,捕获的文本等于整个匹配项。

要“修复”这个问题,您可以使用非捕获组,或者完全删除分组:

std::regex pattern("(?:dl\\.boxcloud\\.com|api-content\\.dropbox\\.com)");
// or
std::regex pattern("dl\\.boxcloud\\.com|api-content\\.dropbox\\.com");

此外,在声明正则表达式时考虑使用原始字符串文字(以避免反斜杠 hell ):

std::regex pattern(R"(dl\.boxcloud\.com|api-content\.dropbox\.com)");

关于c++ - 需要帮助构建正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33744499/

相关文章:

c++ - 在指定的持续时间内运行函数 : C++ with <chrono>

c++ - INSERT into database fetch id 执行后如何获取插入行的ID?

c++ - 同时对象调用

php - 显示不带扩展名的正确 URL,如果 URL 不正确则重定向

java - 我的正则表达式有什么问题吗?

c++ - 澄清迭代器上的后缀/前缀运算符

c++ - 为什么 SetupDiEnumDriverInfo 会为我的驱动程序提供两个版本号

regex - 在 VS Code 中搜索多个术语

Javascript检查字符串中的三个升序字母和数字

javascript - 如何在查找字符串中的所有 url 时停止显示 mailto