c++ regex提取子字符串

C++ regex to extract substring

本文关键字:字符串 提取 regex c++      更新时间:2023-10-16

如何在c++中提取*字符之前的所有字符的子字符串?例如,如果我有一个字符串

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

如何提取

部分
ASDG::DS"G

当然不需要正则表达式。只使用std::string::find('*')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('*'));
}

我认为你的文本没有多个*,因为find返回第一个*

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