解析 c++ 中的字符串,如 python 的解析包
Parsing a string in c++ like python's parse package
在python中,我使用parse
包中的parse
,因此如果我有001-044.mp4
,我可以使用模板{}-{}.mp4
并将其传递给parse
,然后迭代2个结果元素以获得001
和004
。我希望在c++中有一个类似的计数器部分,在这种情况下,我必须根据几个这样的分隔符来解析字符串。有指针吗?
根据示例的复杂程度,可以考虑查看sscanf
或regex
。两者都不遵循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格式函数的东西,你可能需要自己编写。
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- Python 3.7 和 excess_args 的 SWIG 问题
- Python中的for循环与C++有何不同
- 使用Pybind11向Python公开Eigen::张量
- Python str to C++ to Python str
- 如何使用Python从C++中读取谷物序列化数据
- 如何在C++中使用pybind11加载一个pickle python列表
- 如何在c++中使用system()来运行包含空格的python脚本
- python集合的C++等价物是什么.计数器
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 从python调用openMP共享库时,未定义opnMP函数
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- 如何将真正的字符串从python c-api转换为python脚本
- Python ctype 'c_char_p' Memory Leak