解析 c++ 中的字符串,如 python 的解析包

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

本文关键字:python c++ 字符串 解析      更新时间:2023-10-16

在python中,我使用parse包中的parse,因此如果我有001-044.mp4,我可以使用模板{}-{}.mp4并将其传递给parse,然后迭代2个结果元素以获得001004。我希望在c++中有一个类似的计数器部分,在这种情况下,我必须根据几个这样的分隔符来解析字符串。有指针吗?

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

使用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: %dn", 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格式函数的东西,你可能需要自己编写。