通过一个简单的例子来理解c ++正则表达式

17 c++ regex

我写了以下简单的例子:

#include <iostream>
#include <string>
#include <regex>

int main ()
{
    std::string str("1231");
    std::regex r("^(\\d)");
    std::smatch m;
    std::regex_search(str, m, r);
    for(auto v: m) std::cout << v << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

DEMO

并被它的行为搞糊涂了.如果我的理解的目的match_result那里正确,唯一一个1应该被打印出来.其实:

如果成功,它不是空的并且包含一系列sub_match对象:第一个sub_match元素对应于整个匹配, 并且,如果正则表达式包含要匹配的子表达式([...])

传递给函数的字符串与正则表达式不匹配,因此我们应该有the entire match.

我错过了什么?

Gal*_*lik 16

你仍然可以获得整个匹配,整个匹配不适合整个正则表达式整个字符串.

例如,考虑一下:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string str("1231");
    std::regex r("^(\\d)\\d"); // entire match will be 2 numbers

    std::smatch m;
    std::regex_search(str, m, r);

    for(auto v: m)
        std::cout << v << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

12
1
Run Code Online (Sandbox Code Playgroud)

整场比赛(第一sub_match)是什么,整个正则表达式对(字符串的一部分)相匹配.

第二个sub_match是第一个(也是唯一一个)捕获组

看着你原来的正则表达式

std::regex r("^(\\d)");
              |----| <- entire expression (sub_match #0)

std::regex r("^(\\d)");
               |---| <- first capture group (sub_match #1)
Run Code Online (Sandbox Code Playgroud)

这就是两个sub_matches的来源.