【发布时间】:2015-04-16 09:56:28
【问题描述】:
对于这个字符串[268, 950][268, 954][269, 955][272, 955][270, 955][268, 953]
我想逐对获取[ , ] 中的数字。
我使用 c++ regex_search 来解析这个字符串。
这是我的测试代码:
ifstream file("output.txt");
char regex_base[] = "[\\[0-9, 0-9\\]]{10}";
char regex_num[] = "[0-9]{3}";
regex reg_base(regex_base, regex_constants::icase);
regex reg_num(regex_base, regex_constants::icase);
if (file.is_open())
{
string s;
while (!file.eof()){
getline(file, s);
smatch m;
while (regex_search(s, m, reg_num)) {
for (int i = 0; i < m.size(); i++)
cout << m[i] << endl;
}
}
}
但在regex_search() 的while 中,变量m 只能得到[268, 950] 并形成无限循环。
我的正则表达式或代码有什么问题?
【问题讨论】:
-
如果我是你,我会写一个基本算法来做到这一点。
-
这是一个无限循环,因为您在无限循环中对同一个字符串调用它。另外,
while (!file.eof())是错误的。 -
获取字符串中数字的最佳方法是什么,我很困惑。
-
你的模式看起来有点不对劲。试试
"\\[[0-9]+, [0-9]+\\]"