首页 > 解决方案 > 如何使用 regex_search 获取报价中的内容

问题描述

我试图在双引号内获取文本。到目前为止,我只能使用 qoutation 进行打印。我正在使用 regex_search。

文件.txt

"Life is Hard, stay calm." - someone

主文件

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

using namespace std;

int main(){
    ifstream fOpen("file.txt");
    string line0;
    getline(fOpen,line0);
    regex pattern2("(.*) -.*");
    smatch matcher;
    regex_search(line0, matcher, pattern2);
    cout<<matcher[1]<<endl;
    return 0;
}   

到目前为止的输出

"Life is Hard, stay calm."

感谢您的帮助

标签: c++regex

解决方案


试试这个: \"([^\"]*)\"

演示在这里

代码:

int main(){
    ifstream fOpen("file.txt");
    string line0;
    getline(fOpen,line0);
    regex pattern2("\"([^\"]*)\"");
    smatch matcher;
    regex_search(line0, matcher, pattern2);
    cout<<matcher[1]<<endl;
    return 0;
}

推荐阅读