Regular expressions in C++ and extract first integer in string

Some notes on how to use the regular expression support in C++, and how to extract the first integer in a string

To use regular expression, simply construct a regex object, and uses regex_match.

A good post is here

https://www.geeksforgeeks.org/regex-regular-expression-in-c/

Extracting integers from a string is not that easy. However, if we are extracting only a single integer, then we could do the trick

 

// extract the integer from a string
int high_level_schedule::ProgramScheduleNode::extractIntegerFromString(string input_string){

    std::size_t const n = input_string.find_first_of("0123456789");
    if (n != std::string::npos)
    {
        std::size_t const m = input_string.find_first_not_of("0123456789", n);
        return stoi(input_string.substr(n, m != std::string::npos ? m-n : m));
    }
    return -1;

}
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s