如果您想读取这样的输入,最好的方法是什么:
(1,13) { (22,446) (200,66) (77,103) }
(779,22) { } // this is also possible, but always (X,X) in the beginning
我想使用正则表达式来做到这一点。但是,在解析包含多个数字的字符串时,几乎没有关于 reqexp 用法的信息。目前我正在尝试与 sscanf 类似的东西(来自 c 库):
string data;
getline(in, data); // format: (X,X) { (Y,Y)* }
stringstream ss(data);
string point, tmp;
ss >> point; // (X,X)
// (X,X) the reason for three is that they could be more than one digit.
sscanf(point.c_str(), "(%3d,%3d)", &midx, &midy);
int x, y;
while(ss >> tmp) // { (Y,Y) ... (Y,Y) }
{
if(tmp.size() == 5)
{
sscanf(tmp.c_str(), "(%3d,%3d)", &x, &y);
cout << "X: " << x << " Y: " << y << endl;
}
}
问题是这不起作用,只要有超过一位数字,sscanf 就无法读取数字。那么这是最好的方法,还是有更好的正则表达式解决方案?我不想使用 boost 或类似的东西,因为这是学校作业的一部分。
最佳答案
也许下面的代码符合您的要求:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::smatch m;
std::string str("(1,13) { (22,446) (200,66) (77,103) }");
std::string regexstring = "(\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\))\\s*(\\{)(\\s*\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\)\\s*)*\\s*(\\})";
if (std::regex_match(str, m, std::regex(regexstring))) {
std::cout << "string literal matched" << std::endl;
std::cout << "matches:" << std::endl;
for (std::smatch::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << *it << std::endl;
}
}
return 0;
}
输出:
关于c++ - 使用正则表达式解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166748/