Regex C++: extract substring

前端 未结 4 1069
陌清茗
陌清茗 2020-12-02 23:13

I would like to extract a substring between two others.
ex: /home/toto/FILE_mysymbol_EVENT.DAT
or just FILE_othersymbol_EVENT.DAT
And I

4条回答
  •  醉梦人生
    2020-12-02 23:50

    If you want to use regular expressions, I'd really recommend using C++11's regexes or, if you have a compiler that doesn't yet support them, Boost. Boost is something I consider almost-part-of-standard-C++.

    But for this particular question, you do not really need any form of regular expressions. Something like this sketch should work just fine, after you add all appropriate error checks (beg != npos, end != npos etc.), test code, and remove my typos:

    std::string between(std::string const &in,
                        std::string const &before, std::string const &after) {
      size_type beg = in.find(before);
      beg += before.size();
      size_type end = in.find(after, beg);
      return in.substr(beg, end-beg);
    }
    

    Obviously, you could change the std::string to a template parameter and it should work just fine with std::wstring or more seldomly used instantiations of std::basic_string as well.

提交回复
热议问题