C++ regex to extract substring

2019-06-09 05:25发布

问题:

How can I extract a substring in c++ of all the characters before a * character. For example, if I have a string

ASDG::DS"G*0asd}}345sdgfsdfg

how would I extract the portion

ASDG::DS"G

回答1:

You certainly don't need a regular expression for that. Just use std::string::find('*') and std::string::substr:

#include <string>

int main()
{
    // raw strings require C++-11
    std::string s1 = R"(ASDG::DS"G*0asd}}345sdgfsdfg)";
    std::string s2 = s1.substr(0, s1.find('*'));
}


回答2:

I think your text doesn't have multiple * because find return with first *

#include <iostream>
#include <string>

using namespace std;
#define SELECT_END_CHAR "*"

int main(){

    string text = "ASDG::DS\"G*0asd}}345sdgfsdfg";
    unsigned end_index = text.find(SELECT_END_CHAR);
    string result = text.substr (0,end_index);
    cout << result << endl;
    system("pause");
    return 0;
}