【问题标题】:C++ regex to extract substringC++ 正则表达式提取子字符串
【发布时间】:2013-04-11 06:16:40
【问题描述】:

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

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

我将如何提取部分

ASDG::DS"G

【问题讨论】:

    标签: c++ regex string substring


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我认为您的文本没有多个*,因为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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-18
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 1970-01-01
        相关资源
        最近更新 更多