无法在 C++ 中使用正则表达式从字符串中获取所有子字符串

Can't get all substrings from a string using RegEx in C++

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

我想获取与此表达式匹配的所有子字符串:1[0]+1

std::string str =  "0011011000001";
std::regex rx   ("1[0]+1");
std::smatch res;
std::regex_search(str, res, rx);
for (size_t i=0; i<res.size(); i++)
std::cout<<res[i]<<std::endl;

但它只返回我第一个子字符串。我做错了什么?

你应该这样做来获取所有子字符串:

while (std::regex_search (str,res,rx)) {
    std::cout <<res[0] << std::endl;
    str = res.suffix().str();
}

或者您可以使用 std::regex_iterator 获取所有子字符串,如下所示:

std::regex_iterator<std::string::iterator> rit ( str.begin(), str.end(), rx);
std::regex_iterator<std::string::iterator> rend;
while (rit != rend) {
    std::cout << rit->str() << std::endl;
    ++rit;
}

但是当字符串为"00110101000001"时,它仍将输出"101"和"1000001",因为第一个匹配项会消耗部分字符串。如果要查找所有重叠的匹配项,则需要一个支持 Lookaround 断言的正则表达式实现。Python 确实:

>>> re.findall(r'(?=(1[0]+1))', '00110101000001')
['101', '101', '1000001']

(?=... 匹配如果...匹配下一个,但不消耗任何字符串。这称为前瞻断言。例如,Isaac(?=Asimov)只有在后面跟着"Asimov"时才匹配"Isaac"。

使匹配不贪婪...

std::regex rx   ("(1[0]+1)?");