通过一个简单的例子了解C ++正则表达式 [英] Understanding c++ regex by a simple example

查看:87
本文介绍了通过一个简单的例子了解C ++正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下简单示例:

I wrote the following simple example:

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

演示

DEMO

,并对其行为感到困惑。如果我了解> match_result 的目的正确地打印了唯一的 1 。实际上:

and got confused by its behavior. If I understood the purpose of the match_result from there correctly, the only one 1 should have been printed. Actually:


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

If successful, it is not empty and contains a series of sub_match objects: the first sub_match element corresponds to the entire match, and, if the regex expression contained sub-expressions to be matched ([...])

传递给函数的字符串与正则表达式不匹配,因此我们应该具有整个匹配项

The string passed to the function doesn't match the regex, therefore we should not have had the entire match.

我错过了什么?

推荐答案

您仍然得到了整个匹配,但整个匹配不适合整个字符串,它适合整个正则表达式

You still get the entire match but the entire match does not fit the entire string it fits the entire regex.

例如,请考虑以下问题:

For example consider this:

#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

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

The entire match (first sub_match) is what the entire regex matches against (part of the string).

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

The second sub_match is the first (and only) capture group

查看原始的 regex

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

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

这是两个 sub_matches 来自。

这篇关于通过一个简单的例子了解C ++正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆