繁体   English   中英

解析 c++ 中的字符串,就像 python 的解析 package

[英]Parsing a string in c++ like python's parse package

在 python 中,我使用parse package 中的parse ,所以如果我有001-044.mp4 ,我可以使用模板{}-{}.mp4并将其传递给parse和迭代 2 个结果元素以获得001004 在我必须根据几个这样的分隔符解析字符串的情况下,我想要 c++ 中的类似对应部分。 任何指针?

根据您的示例有多复杂,请考虑查看sscanfregex 两者都不遵循 pythonic 语法,但可以用来做同样的事情。

使用 sscanf:

#include <cstdio>

int main()
{
  const char* text = "012-231.mp4";

  int a = 0, b = 0;
  sscanf(text, "%d-%d.mp4", &a, &b);

  printf("First number: %d, second number: %d\n", a, b);
}

使用正则表达式:

#include <iostream>
#include <regex>
#include <string>

int main()
{
  std::string text = "012-231.mp4";

  std::regex expr("([0-9]*)-([0-9]*).mp4");

  std::smatch match;
  std::regex_match(text, match, expr);

  std::cout << "The matches are: ";
  // Start from i = 1; the first match is the entire string
  for (unsigned i = 1; i < match.size(); ++i) {
    std::cout << match[i] << ", ";
  }
  std::cout << std::endl;
}

如果您正在寻找行为严格类似于 python 格式 function 的东西,您可能必须自己编写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM