簡體   English   中英

通過一個簡單的例子來理解c ++正則表達式

[英]Understanding c++ regex by a 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 其實:

如果成功,它不是空的並且包含一系列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,則整個字符串必須匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM