c++ - 使用正则表达式解析字符串

标签 c++ regex

如果您想读取这样的输入,最好的方法是什么:

(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;
}

输出:

enter image description here

关于c++ - 使用正则表达式解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166748/

相关文章:

c++ - DER 格式的 X509 证书是否采用 ASN1 编码?

c++ - 映射类导致内存泄漏

c++ - 如何使用 itk 对 tif 文件图像进行插值?

c++ - 有没有什么算法可以将简单的 Haxe 代码转换为 C/C++ 代码文件?

c++ - 在 main 的 return 0 语句之后可以调用任何函数吗?

C++ 正则表达式替换第一个匹配项

regex - Emacs 组织模式链接格式化

java - 正则表达式,匹配不带 "http://"和任何其他 "/"的url

python - Python 和 re2c 正则表达式中字符集的区别

正则表达式每个字母只使用一次?