c++ - 如何从cpp中的给定字符串中提取特定字符串?

标签 c++ string split substring

我有以下名为标题的字符串:"bla bla hello, just more characters filename="myfile.1.2.doc"more characters"

我需要从这个字符串中获取文件名和文件类型,但我的解决方案似乎很乱(伪代码):

unsigned int end = header.find("filename=");
unsigned int end2 = header.find(" " ", end + sizeof("filename=") + 1) // how to search for ' " ' ?!

std::string fullFileName = header.substr(end +sizeof("filename=") + 1 ,end2 -1);
//now look for the first "." from the end and split by that .

cpp中如何从末尾看?

最佳答案


我觉得用正则表达式会更好
例如:我们有更复杂的字符串,其中包含一些文件名和文件名外的 (") 等令人困惑的字符。

std::string str("bla bla hello, just more characters filename=\"myfile.1.2.doc\" more characters bla bla hello, just more characters filename=\"newFile.exe\" more char\"acters");
std::smatch match;
std::regex regExp("filename=\"(.*?)\\.([^.]*?)\"");

while (std::regex_search(str, match, regExp))
{
    std::string name = match[1].str();
    std::string ext = match[2].str();
    str = match.suffix().str();
}

第一次迭代给你:
name = myfile.1.2
ext = 文档
第二:
name = 新文件
ext = exe

关于c++ - 如何从cpp中的给定字符串中提取特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30967079/

相关文章:

java - 按 {} 和 [] 拆分字符串

C++ 转换为派生结构和父结构

c++ - 在编译时构造对象并存储在可执行文件中?

c++ - 使用基本模板标识符时继承

java - 不区分大小写的字符串过滤器

python - Python 中的英文键盘文本到俄语

python - 如何使用定界符在 Ansible 中拆分值

c++ - std::getline(), while 循环内容未运行

android - 在 Android 中,_id 是否必须存在于任何创建的表中?

r - 将数据分解为每个级别并向其应用函数