C++11 场比赛中的正则表达式匹配

C++11 regex matches within matches

本文关键字:正则表达式 C++11      更新时间:2023-10-16

是否可以遍历所有匹配项,包括匹配项中的匹配项?

我正在尝试从我的字符串中提取oook outsideo开头的子字符串,这些子字符串以不同的字符结尾:即 oookookokou

我认为以下代码可以做到这一点:

#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
    string s = "oook outside";
    regex e("o+[a-z]");
    sregex_iterator it(s.begin(), s.end(), e);
    sregex_iterator it_end;
    while (it != it_end) {
        cout << it->str() << endl;
        it++;
    }
    return 0;
}

相反,它只打印oookou

匹配所有内容,但不消耗任何内容。
引擎将在每场比赛
中将位置提高 1 个消耗字符。

若要查看匹配项,请将其包装到捕获组中。

(?=(o+[a-z]))

扩大

 (?=
      ( o+ [a-z] )                  # (1)
 )

如果引擎没有碰到它,那么你总是可以手动消耗 1。
要匹配它,但消耗 1 次使用:

(?=(o+[a-z]))o

扩大

 (?=
      ( o+ [a-z] )                  # (1)
 )
 o

两者是等效的。从捕获组 1 获取结果。

比赛

 **  Grp 0 -  ( pos 0 , len 0 )  EMPTY 
 **  Grp 1 -  ( pos 0 , len 4 ) 
oook  
--------------------
 **  Grp 0 -  ( pos 1 , len 0 )  EMPTY 
 **  Grp 1 -  ( pos 1 , len 3 ) 
ook  
--------------------
 **  Grp 0 -  ( pos 2 , len 0 )  EMPTY 
 **  Grp 1 -  ( pos 2 , len 2 ) 
ok  
--------------------
 **  Grp 0 -  ( pos 5 , len 0 )  EMPTY 
 **  Grp 1 -  ( pos 5 , len 2 ) 
ou  

知道了!

int main() {
    string s = "oook outside";
    smatch m;
    regex e("(?=(o+[a-z]))o");  // "o+[a-z]";
    while (regex_search(s, m, e)) {
        cout << m[1] << endl;
        s = m.suffix();
    }
    return 0;
}

谢谢大家!