gpt4 book ai didi

c++ - C++正则表达式无限循环

转载 作者:行者123 更新时间:2023-12-01 14:52:07 24 4
gpt4 key购买 nike

我正在写一个正则表达式的c++程序来查找给定Excel范围字符串中提到的单元格
例如
$ C $ 5
$ CC $ 4
$ C $ 5:$ F $ 89
因为只需要匹配一次(即在字符串中仅提及一个单元格)或两次(即当字符串中提及两个单元格;其范围)时,我才设计了程序:

    //get the cell being mentioned
std::regex regx("\\$(\\w+)\\$(\\d+)");
std::smatch match;
//match[0] = whole match (only useful for debug)
//match[1] = first cell col letter ; match[2] = first cell row numb
//match[3] = second cell col letter; match[4] = second cell row numb
/*vectors for putting columns and rows values extracted in the while loop into*/
std::vector<std::string> vecCol;
std::vector<std::string> vecRow;

//put all substring matches into a vector - This loop runs infinitely
while (std::regex_search(inString.begin(),inString.end(), match, regx)) {
std::cout << match[0] << "\n";
//add them to the vecs
vecCol.push_back(match[1].str());
vecRow.push_back(match[2].str());
}
while循环会导致我不太了解的问题;它陷入无限循环,并在每次无限循环时继续添加相同的子字符串匹配项(例如C4)。即使传入的字符串中仅提到一个单元格,也会发生这种情况
请谁能解释我对此C++正则表达式有何疑问?

最佳答案

while循环内部,您无需更改inString,也无需使用将移动正则表达式索引的迭代器,因此您会不断获得一个相同的匹配项,并且循环内没有break条件。
使用

while (std::regex_search(inString, match, regx)) {
std::cout << match[0] << "\n";
vecCol.push_back(match[1].str());
vecRow.push_back(match[2].str());
inString = match.suffix().str();
参见 C++ demo。输出: $C$5$F$89
请注意,它将更改 inString。如果您不想要它,请使用 sregex_iterator:
for(std::sregex_iterator i = std::sregex_iterator(inString.begin(), inString.end(), regx);
i != std::sregex_iterator();
++i)
{
std::smatch match = *i;
std::cout << "Whole match: " << match.str() << ", Group 1: " << match.str(1) << ", and Group 2: " << match.str(2) << '\n';
//add them to the vecs
vecCol.push_back(match.str(1));
vecRow.push_back(match.str(2));
}
参见 C++ demo,输出:
Whole match: $C$5, Group 1: C, and Group 2: 5
Whole match: $F$89, Group 1: F, and Group 2: 89

关于c++ - C++正则表达式无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62721097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com