简体   繁体   中英

C++ regex to extract substring

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

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('*'));
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM