C++ Extract number from the middle of a string

后端 未结 8 753
南方客
南方客 2020-12-03 07:27

I have a vector containing strings that follow the format of text_number-number

Eg: Example_45-3

8条回答
  •  旧巷少年郎
    2020-12-03 07:36

    updated for C++11

    (important note for compiler regex support: for gcc. you need version 4.9 or later. i tested this on g++ version 4.9[1], and 9.2. cppreference.com has in browser compiler that i used.)

    Thanks to user @2b-t who found a bug in the c++11 code!

    Here is the C++11 code:

    #include 
    #include 
    #include 
    
    using std::cout;
    using std::endl;
    
    int main() {
        std::string input = "Example_45-3";
        std::string output = std::regex_replace(
            input,
            std::regex("[^0-9]*([0-9]+).*"),
            std::string("$1")
            );
        cout << input << endl;
        cout << output << endl;
    }
    

    boost solution that only requires C++98

    Minimal implementation example that works on many strings (not just strings of the form "text_45-text":

    #include 
    #include 
    using namespace std;
    #include 
    
    int main() {
        string input = "Example_45-3";
        string output = boost::regex_replace(
            input,
            boost::regex("[^0-9]*([0-9]+).*"),
            string("\\1")
            );
        cout << input << endl;
        cout << output << endl;
    }
    

    console output:

    Example_45-3
    45
    

    Other example strings that this would work on:

    • "asdfasdf 45 sdfsdf"
    • "X = 45, sdfsdf"

    For this example I used g++ on Linux with #include and -lboost_regex. You could also use C++11x regex.

    Feel free to edit my solution if you have a better regex.


    Commentary:

    If there aren't performance constraints, using Regex is ideal for this sort of thing because you aren't reinventing the wheel (by writing a bunch of string parsing code which takes time to write/test-fully).

    Additionally if/when your strings become more complex or have more varied patterns regex easily accommodates the complexity. (The question's example pattern is easy enough. But often times a more complex pattern would take 10-100+ lines of code when a one line regex would do the same.)


    [1]

    [1] Apparently full support for C++11 was implemented and released for g++ version 4.9.x and on Jun 26, 2015. Hat tip to SO questions #1 and #2 for figuring out the compiler version needing to be 4.9.x.

提交回复
热议问题