3

Ok, so I'm working with C++ regex and I'm not quite sure how to go about extracting the numbers that I want from my expression.

I'm building an expression BASED on numbers, but not sure how to pull them back out.

Here's my string:

+10.7% Is My String +5 And Some Extra Stuff Here

I use that string to pull the numbers 10 , 7 , 5 out and add them to a vector, no big deal. I then change that string to become a regex expression.

\+([0-9]+)\.([0-9]+)% Is My String \+([0-9]+) And Some Extra Stuff Here

Now how do I go about using that regexp expression to MATCH my starting string and extracting the numbers back out.

Something along the lines of using the match table?

Casper7526
  • 341
  • 3
  • 13
  • possible duplicate of [Retrieving a regex search in C++](http://stackoverflow.com/questions/12908534/retrieving-a-regex-search-in-c) – Bastien Jun 10 '15 at 08:50

1 Answers1

3

You must iterate over the submatches to extract them.

Example:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string input = "+10.7% Is My String +5 And Some Extra Stuff Here";
    std::regex rx("\\+([0-9]+)\\.([0-9]+)% Is My String \\+([0-9]+) And Some Extra Stuff Here");

    std::smatch match;

    if (std::regex_match(input, match, rx))
    {
        for (std::size_t i = 0; i < match.size(); ++i)
        {
            std::ssub_match sub_match = match[i];
            std::string num = sub_match.str();
            std::cout << " submatch " << i << ": " << num << std::endl;
        }   
    }
}

Output:

 submatch 0: +10.7% Is My String +5 And Some Extra Stuff Here
 submatch 1: 10
 submatch 2: 7
 submatch 3: 5

live example: https://ideone.com/01XJDF

m.s.
  • 16,063
  • 7
  • 53
  • 88
  • Thank you so much, I was messing around with just match for so long... I didn't even know sub_match was a thing LOL. – Casper7526 Jun 10 '15 at 09:59