通过一个简单的示例了解 c++ 正则表达式

Understanding c++ regex by a simple example

本文关键字:了解 正则表达式 c++ 简单 一个      更新时间:2023-10-16

我写了以下简单的例子:

#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;
}

演示

并对其行为感到困惑。如果我从那里正确理解了match_result的目的,那么应该打印唯一的1。实际上:

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

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

我错过了什么?

您仍然可以获得整个匹配项,但整个匹配项不适合整个字符串,它适合整个正则表达式

例如,考虑一下:

#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;
}

输出:

12
1

整个匹配项(第一个sub_match)是整个正则表达式匹配的对象(字符串的一部分)。

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

查看您的原始正则表达式

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

这就是两个sub_matches的来源。

从这里开始

    Returns whether **some** sub-sequence in the target sequence (the subject) 
    matches the regular expression rgx (the pattern). The target sequence is 
    either s or the character sequence between first and last, depending on 
    the version used.

因此regex_search将在输入字符串中搜索与正则表达式匹配的任何内容。整个字符串不必匹配,只需匹配其中的一部分。

但是,如果要使用 regex_match,则整个字符串必须匹配。